//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}); })