node.js调用接口getUnlimite获取小程序码乱码

这篇博客讲述了在获取微信小程序二维码时遇到的问题。原始代码由于默认使用了'utf-8'编码导致返回的数据出现乱码。通过查阅request库的官方文档,了解到在处理二进制数据如图片时,需要将`encoding`设置为`null`。修复这个问题后,成功地将返回的二进制数据转换为base64编码,并保存为图片文件。最后,将base64编码发送到响应中。
源代码:
       request({
             url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + token,
                    method: "POST",
                    json: true,
                    headers: {
                        "content-type": "application/json",
                    },
                    body: {
                        "path": "pages/index/index",
                        "scene": 'a=1'
                    },
                    responseType: 'arraybuffer'
                }, function(error, response, body) {
                    if (!error && response.statusCode == 200) {
                         console.log(body);
                        // let tempo = new Buffer.from(body, 'binary')
                        // tempo = tempo.toString('base64');
                        base64 = 'data:image/png;base64,' + body.toString('base64');
                       // console.log(base64);
                        fs.writeFileSync('./图片base.txt', base64, 'utf-8');
                        fs.writeFileSync('./图片.jpg', body);
                        res.send(base64)
                    }
                });
            }

结果

乱码
在这里插入图片描述问题原因
查看request官方文档发现默认使用utf-8编码
在这里插入图片描述

(Note: if you expect binary data, you should set encoding: null.) 注意:如果你需要二进制数据(图片就属于这一类别),你应该将编码格式设成null。
然后,按照官网文档的建议,我设置了下,奇迹发生了

 request({
    url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + token,
    method: "POST",
    json: true,
    headers: {
                        "content-type": "application/json",
               },
   encoding: null,
   body: {
                        "path": "pages/index/index",
                        "scene": 'a=1'
           },
   responseType: 'arraybuffer'
           }, function(error, response, body) {
   if (!error && response.statusCode == 200) {
             console.log(body);
             // let tempo = new Buffer.from(body, 'binary')
              // tempo = tempo.toString('base64');
              base64 = 'data:image/png;base64,' +   body.toString('base64');
               // console.log(base64);
            fs.writeFileSync('./图片base.txt', base64, 'utf-8');
            fs.writeFileSync('./图片.jpg', body);
            res.send(base64)
                    }
                });

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值