NodeJs后台ReactNative前端实现图形验证码功能

NodeJs 后台

使用 express 框架搭建的后台

1. 安装 svg-captcha

npm i svg-captcha --save

2.生成图形验证码

import svgCaptcha from 'svg-captcha';
const vertifyCode = svgCaptcha.create({width:90, height:25, background: '#cccccc', color: true, noise: 2, ignoreChars: '0oO1iIl', fontSize: 30});

background: ‘#cccccc’, color: true,
//设置字体为彩色,设置了background,color才能生效

noise: 2,
//干扰线条数

ignoreChars: ‘0oO1iIl’,
//排除掉容易混淆的字

3.获取生成的码和图片

vertifyCode.text //生成的随机码

vertifyCode.data //生成的 svg 图片

ReactNative 前台 App 页面

1.安装 react-native-svg,ReactNative 本身不支持显示 svg 图片

npm i react-native-svg --save

2.使用

import Svg, {Path, Rect} from 'react-native-svg';

3.从后台获取到数据是字符串格式,所以需要自行处理后输出

_svgShow(svgImg){
      //处理字符串
      const svgImg1=svgImg.replace(/svg/g,"Svg");
      const svgImg2=svgImg1.replace(/path/g,'Path');
      const svgImg3=svgImg2.replace(/\'/g,'');
      const svgImg4=svgImg3.split('><Path');

      return (
        <Svg style={styles.code_svg}>
          {svgImg4.map((item,i) => {
            if(i!==0 && i!==svgImg4.length){
              let fill = "";
              let d = "";
              let stroke = "";
              const pathList = item.split('=');
              if(pathList.length==3){
                 fill = pathList[1].split(' ')[0].replace(/\"/g, "");
                 d = pathList[2].replace(/([\"\/]|><\/Svg>)/g, "");
                 stroke = "";
              } else if(pathList.length==4) {
                 fill = "none";
                 d = pathList[1].split('" ')[0].replace(/[\"\/]/g, "");
                 stroke = pathList[2].split(' ')[0];
              }
              return <Path key={i} fill={fill} d={d}  />
            }
          })}
        </Svg>
      )
    }