前言:
使用nodejs开发时,有时需要调用外部接口,比如我们要写一个小程序的接口,需要请求微信的接口,egg里面提供了curl方法来实现调用外部接口。
目录:
4、如果返回的数据是流的格式,需要转换成字符,再进行处理,示例代码如下:
实现方法:
1、案例方法:
async wxOpenid() {
const { ctx } = this;
const { js_code } = ctx.request.body;
const { data } = await this.ctx.curl('https://api.weixin.qq.com/sns/jscode2session', {
method: 'GET',
rejectUnauthorized: false,
data: {
appid: wxConfig.appid, // 你的小程序的APPID
secret: wxConfig.secret, // 你的小程序的secret,
js_code, // wx.login 登录成功后的code
},
dataType: 'json',
})
this.ctx.body = data;
}
2、get/post方法请求:
this.ctx.curl('外部后台地址',
{
method: 'POST', //请求方法 GET/POST
data: {
参数
},
headers:{ //自定义header,如果header需要参数,写在这里
"Accept": "*/*",
"Content-Type":"application/json"
},
dataType: 'json' //返回格式
})
3、如果是https请求的话,
校验证书:
const cerPaht = '你本地/或者线上的证书地址'
fs.readFileSync(cerPaht)
this.ctx.curl('外部后台地址',
{
method: 'POST', //请求方法 GET/POST
rejectUnauthorized: true, //是否校验证书
cert: fs.readFileSync(cerPaht),//对证书格式有要求
data: {
参数
}
dataType: 'json' //返回格式
})
不校验证书:(用的多)
this.ctx.curl('外部后台地址',
{
method: 'POST', //请求方法 GET/POST
rejectUnauthorized: false, //是否校验证书
data: {
参数
}
dataType: 'json' //返回格式
})
4、如果返回的数据是流的格式,需要转换成字符,再进行处理,示例代码如下:
let res =yield this.ctx.curl('http:xxx.com/api');
let json=JSON.parse(res.data.toString());
到此为止!