0
点赞
收藏
分享

微信扫一扫

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


源代码:

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

结果

乱码

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

问题原因

查看request官方文档发现默认使用utf-8编码

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

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

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


举报

相关推荐

0 条评论