Angular2+nodejs 图片验证码的实现

//login.component.ts
import { DomSanitizer } from '@angular/platform-browser';//用来转换innerhtml
import { CookieService } from 'ngx-cookie-service';
import { ActivatedRoute, Router } from "@angular/router";
import { CaptchapngService } from '../../../core/services/captchapng.service'
constructor(
    private activatedRoute: ActivatedRoute,
    private CaptchapngService: CaptchapngService,
    private DomSanitizer: DomSanitizer,
    private Router:Router,
    private CookieService: CookieService,
) {
  ....
}
....
//svg获取验证码的方法,借助nodejs的svg-captcha getSvgCaptchapng() { if(event){ event.preventDefault(); } this.CaptchapngService.getSvgCaptch().subscribe( (res: Response) => { let body = res.json() if (body && body.success) { this.CookieService.set('tempYz', body.data.tempsession) this.Yzimg = this.DomSanitizer.bypassSecurityTrustHtml(body.data.img); //将<svg></svg>转换一下,方便在页面上使用innerHTML } } ) }

service

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators'
@Injectable()
export class CaptchapngService {
    constructor(private http: Http) {
    }
    //通用
    private handleError<T>(operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {
            return of(result as T);
        }
    }
    getSvgCaptch() {
        let data = {
            size: 4,  //验证码长度
            width: 200,
            height: 100,
            background: "#f4f3f2",//干扰线条数
            noise: 2,
            fontSize: 60,
            ignoreChars: '0o1i',   //验证码字符中排除'0o1i'
            color: true // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有 
        }
        return this.http.post('http://localhost:5000/user/svg-captcha', data).pipe(
            map((res: any) => res),
            catchError(this.handleError('getSvgCaptchhandleError'))
        )
    }
}

nodejs

const svgCaptcha = require('svg-captcha');

//获取svg验证码
server.post('/user/svg-captcha',(req,res)=>{
    console.log('getsvg-captcha......')
     var option = req.body;
    // 验证码,有两个属性,text是字符,data是svg代码
    var code = svgCaptcha.create(option);
    // 返回数据直接放入页面元素展示即可
    data = {
        img: code.data,
        tempsession: code.text.toLowerCase()
    }
    res.json({'success':true, data:data});
})