如何从Node.js或Express.js中发出HTTP请求?我需要连接到另一个服务。我希望调用是异步的,并且回调包含远程服务器的响应。
当前回答
Unirest是我遇到的用于从Node发出HTTP请求的最好的库。它的目标是成为一个多平台框架,所以如果你需要在Ruby、PHP、Java、Python、Objective C、. net或Windows 8上使用HTTP客户端,学习它在Node上的工作方式会对你很有帮助。据我所知,unirest库大多是由现有的HTTP客户端支持的(例如,在Java上,Apache的HTTP客户端,在Node上,Mikeal的Request库)——unirest只是在上面放了一个更好的API。
下面是Node.js的一些代码示例:
var unirest = require('unirest')
// GET a resource
unirest.get('http://httpbin.org/get')
.query({'foo': 'bar'})
.query({'stack': 'overflow'})
.end(function(res) {
if (res.error) {
console.log('GET error', res.error)
} else {
console.log('GET response', res.body)
}
})
// POST a form with an attached file
unirest.post('http://httpbin.org/post')
.field('foo', 'bar')
.field('stack', 'overflow')
.attach('myfile', 'examples.js')
.end(function(res) {
if (res.error) {
console.log('POST error', res.error)
} else {
console.log('POST response', res.body)
}
})
您可以直接跳转到Node文档
其他回答
看看shred。它是由spire创建和维护的节点HTTP客户端。io处理重定向、会话和JSON响应。它非常适合与rest api交互。详见这篇博客文章。
下面是我的一个示例中的一些代码片段。它是异步的,返回一个JSON对象。它可以执行任何形式的GET请求。
请注意,有更多的最佳方法(只是一个例子)-例如,而不是将你放入数组中的块连接起来,等等…希望它能让你从正确的方向开始:
const http = require('http');
const https = require('https');
/**
* getJSON: RESTful GET request returning JSON object(s)
* @param options: http options object
* @param callback: callback to pass the results JSON object(s) back
*/
module.exports.getJSON = (options, onResult) => {
console.log('rest::getJSON');
const port = options.port == 443 ? https : http;
let output = '';
const req = port.request(options, (res) => {
console.log(`${options.host} : ${res.statusCode}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
output += chunk;
});
res.on('end', () => {
let obj = JSON.parse(output);
onResult(res.statusCode, obj);
});
});
req.on('error', (err) => {
// res.send('error: ' + err.message);
});
req.end();
};
它是通过创建一个选项对象来调用的,比如:
const options = {
host: 'somesite.com',
port: 443,
path: '/some/path',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
并提供一个回调函数。
例如,在一个服务中,我需要上面的REST模块,然后这样做:
rest.getJSON(options, (statusCode, result) => {
// I could work with the resulting HTML/JSON here. I could also just return it
console.log(`onResult: (${statusCode})\n\n${JSON.stringify(result)}`);
res.statusCode = statusCode;
res.send(result);
});
更新
如果你正在寻找异步/等待(线性,无回调),承诺,编译时支持和智能感知,我们创建了一个轻量级的HTTP和REST客户端,符合要求:
微软typed-rest-client
对于任何想要在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发送请求。目前,这是一个实验性的功能,所以要小心。
如果你需要向一个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) => { ......
看看httpreq:这是我创建的一个节点库,因为我很沮丧,没有简单的http GET或POST模块;-)
推荐文章
- 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中配置不同的环境?