如何从Node.js或Express.js中发出HTTP请求?我需要连接到另一个服务。我希望调用是异步的,并且回调包含远程服务器的响应。
当前回答
如果你需要向一个IP和一个域发送GET请求(其他答案没有提到你可以指定一个端口变量),你可以使用这个函数:
function getCode(host, port, path, queryString) {
console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")
// Construct url and query string
const requestUrl = url.parse(url.format({
protocol: 'http',
hostname: host,
pathname: path,
port: port,
query: queryString
}));
console.log("(" + host + path + ")" + "Sending GET request")
// Send request
console.log(url.format(requestUrl))
http.get(url.format(requestUrl), (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
console.log("GET chunk: " + chunk);
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log("GET end of response: " + data);
});
}).on("error", (err) => {
console.log("GET Error: " + err);
});
}
不要错过文件顶部的require模块:
http = require("http");
url = require('url')
另外请记住,您可以使用https模块在安全的网络上进行通信。所以这两条线会改变:
https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......
其他回答
对于任何想要在NodeJS中发送HTTP请求的库的人来说,axios也是一个不错的选择。它支持Promises:)
Install (npm)
示例GET请求:
const axios = require('axios');
axios.get('https://google.com')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
Github页面
更新10/02/2022
Node.js在实验模式下集成了v17.5.0中的fetch。现在,您可以像在客户端一样使用fetch发送请求。目前,这是一个实验性的功能,所以要小心。
Request和Superagent是非常好的库。
注意:请求已弃用,使用风险自负!
使用要求:
var request=require('request');
request.get('https://someplace',options,function(err,res,body){
if(err) //TODO: handle err
if(res.statusCode === 200 ) //etc
//TODO Do something with response
});
看看shred。它是由spire创建和维护的节点HTTP客户端。io处理重定向、会话和JSON响应。它非常适合与rest api交互。详见这篇博客文章。
看看httpreq:这是我创建的一个节点库,因为我很沮丧,没有简单的http GET或POST模块;-)
你也可以使用Requestify,这是我为nodeJS +编写的一个非常酷且非常简单的HTTP客户端,它支持缓存。
只需对GET方法请求执行以下操作:
var requestify = require('requestify');
requestify.get('http://example.com/api/resource')
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
response.getBody();
}
);
推荐文章
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie
- 如何使用npm全局安装一个模块?
- 如何减去日期/时间在JavaScript?
- 如何检测“搜索”HTML5输入的清除?
- 字符串中的单词大写
- 返回一个正则表达式匹配()在Javascript的位置?
- Ajax成功事件不工作
- 为什么JavaScript中弃用arguments.callee.caller属性?
- 在typescript中一直使用。tsx而不是。ts有什么缺点吗?
- 实时http流到HTML5视频客户端的最佳方法
- 如何在Angular.js中配置不同的环境?