使用 got 进行网络请求的步骤:
1.创建云函数,并在终端执行云函数
2.执行 npm 安装 got ,命令:cnpm install --save got
3.在云函数中使用
示例代码:
// 云函数入口文件
const cloud = require('wx-server-sdk')
const got = require('got');
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
const page = event.page
//appid和秘钥
const appid = 'xxxx',secret = 'xxxx';
const resultValue_options = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
appid,
secret,
grant_type: 'client_credential'
})
};
var url1 = 'https://api.weixin.qq.com/cgi-bin/token?appid=' + appid + '&secret=' + secret + '&grant_type=client_credential'
const body = await got(url1).json();
const token = body.access_token;
var url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + token;
//获取小程序码配置
const code_options =
{
methods: 'post',
body: JSON.stringify({
'width': 200,
'scene': 'scene_' + new Date().getTime()
})
}
//获取二进制图片
const buffer = await got.post(url, code_options);
const upload = await cloud.uploadFile({
cloudPath: 'code/' + new Date().getTime()+'.png',
fileContent: buffer,
})
return {
wxacodefileID: upload.fileID
}
}