nodejs调用小程序生成二维码接口,并保存成图片

小程序生成二维码接口返回的是二进制,所以我们要把二进制流保存成图片,再返回给前端。

这里我分别用axiosrequest实现请求

获取token

1
const {data: { access_token }} = await axios.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET')

axios

1
2
3
4
5
6
7
8
9
10
11
axios({
method: 'post',
url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${access_token}`,
data: {
path: ''
},
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('path.jpg'))
})

request

1
2
3
4
5
6
7
8
9
10
request.post({
url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${access_token}`,
json: true,
headers: { 'content-type': 'application/json' },
body: {
path: ''
}
}, function (error, response, body) {
res.send(imgUrl)
}).pipe(fs.createWriteStream('path.png'))