首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Express实现生成二维码接口

Express实现生成二维码接口

作者头像
越陌度阡
发布2020-11-26 16:33:48
发布2020-11-26 16:33:48
8760
举报
代码语言:javascript
复制
// 引入模块
const express=require('express');
const QRCode=require('qr-image');

// 生成服务器
var server=express();

// 查询接口
server.get('/code',(req,res)=>{
    // 模拟的请求接口地址
    var str='http://localhost:8090/code?url=https://www.baidu.com/&size=210&margin=10&type=1'

    var url=req.query.url;

    // 二维码尺寸,输入时为了保证精确性,请确保为21的公倍数,否则按四舍五入处理.
    // 如果为空,默认为5,即尺寸为105*105
    var size = Math.round(req.query.size/21) || 5;

    // 白色外边距,输入时为了保证精确性,请确保为5的公倍数,否则按四舍五入处理.
    // 如果为空,默认为2,即尺寸为10
    var margin = Math.round(req.query.margin/10) || 2 ;

    var type=req.query.type;

    // 如果有type参数,返回base64
    if(type){
        var codeStr = QRCode.imageSync( url ,{ type: 'png',size:size, margin:margin});
        var base64='data:image/jpeg;base64,'+ codeStr.toString('base64');
        res.writeHead(200, {'Content-Type':'text/plain;charset=UTF-8'}); 
        res.end(base64);
    // 如果没有type参数,返回图片
    }else{
        var code = QRCode.image( url ,{ type: 'png',size:size, margin:margin});
        res.writeHead(200, {'Content-Type': 'image/png;charset=UTF-8'});
        code.pipe(res);
    }
});

server.listen(8090);
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/05/05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档