superagent是一个轻量级的Ajax api,既可以在服务端的nodejs中使用,也可以在客户端的javascript中使用,其api相对简单易上手。大家在工作中应该经常会使用到,但是superagent通过代理去调用服务,应该很少使用,下面就给大家具体介绍下如何使用:
由于superagent本身不支持代理的方式进行http请求,因此需要借助第三方的模块,本文介绍的是superagent-proxy。
$ npm install superagent-proxy
var request = require('superagent');
// extend with Request#proxy()
require('superagent-proxy')(request);
// HTTP, HTTPS, or SOCKS proxy to use
var proxy = process.env.http_proxy || 'http://168.63.43.102:3128';
request
.get(process.argv[2] || 'https://encrypted.google.com/')
.proxy(proxy)
.end(onresponse);
function onresponse (err, res) {
if (err) {
console.log(err);
} else {
console.log(res.status, res.headers);
console.log(res.body);
}
}
const superagent = require('superagent');
// callback
superagent
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
.set('X-API-Key', 'foobar')
.set('accept', 'json')
.end((err, res) => {
// Calling the end function will send the request
});
// promise with then/catch
superagent.post('/api/pet').then(console.log).catch(console.error);
// promise with async/await
(async () => {
try {
const res = await superagent.post('/api/pet');
console.log(res);
} catch (err) {
console.error(err);
}
})();
参考:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有