发布时间:2024-08-25 17:01
nodejs开发时候,如果涉及远程rpc调用api接口,发送get,post请求,可以自己用http封装,也可以使用第三方npm包来实现,结合之前开发中的使用,发现superagent这个npm包很好用,微信支付的文档里也建议用这个包。
post
var simpleSendPostRequest = function (url, params) {
return new Promise ((resolve) => {
request.post(url).send(params).set({
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
}).end(function(req,res){
try {
resolve({"success": true, "data": res.text});
} catch (e) {
log.error(e);
resolve({"success": false});
}
})
})
}
get
var simpleSendGetRequest = function (url, params) {
return new Promise ((resolve) => {
// params入参'mchid=111' 代表get请求参数http://api.mo.com/pay?mchid=111
request.get(url).query(params).set({
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
}).end(function(req,res){
try {
resolve({"success": true, "data": res.text});
} catch (e) {
log.error(e);
resolve({"success": false});
}
})
})
}