Node.js Express中的HTTP GET请求 [英] HTTP GET Request in Node.js Express
问题描述
如何从node / express内部发出HTTP请求?我需要连接到另一个服务。我希望通话是异步的,回调包含远程服务器响应。
How can I make an HTTP request from within node/express? I need to connect to another service. I am hoping the call is async and that the callback contains the remote servers response.
推荐答案
这是我的一个示例的代码。它是异步的,并返回一个JSON对象。它可以做任何获取请求。注意,有更多的最佳方法(只是一个示例) - 例如,而不是连接到你放入数组的块,并加入它等等。希望它可以从正确的方向开始:
Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:
var http = require("http");
var https = require("https");
/**
* getJSON: REST get request returning JSON object(s)
* @param options: http options object
* @param callback: callback to pass the results JSON object(s) back
*/
exports.getJSON = function(options, onResult)
{
console.log("rest::getJSON");
var port = options.port == 443 ? https : http;
var req = port.request(options, function(res)
{
var output = '';
console.log(options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function() {
var obj = JSON.parse(output);
onResult(res.statusCode, obj);
});
});
req.on('error', function(err) {
//res.send('error: ' + err.message);
});
req.end();
};
通过创建一个选项对象,如:
It's called by creating an options objects like:
var options = {
host: 'somesite.com',
port: 443,
path: '/some/path',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
并提供回调功能。
例如,在一个服务中,我需要上面的其他模块,然后这样做。
For example, in a service, I require the rest module above and then do this.
rest.getJSON(options, function(statusCode, result) {
// I could work with the result html/json here. I could also just return it
console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
res.statusCode = statusCode;
res.send(result);
});
更新:
如果你是寻找异步等待(线性无回调),承诺,编译时支持和智能感知,我们创建一个适合该帐单的轻量级http和休息客户端:
If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:
https://github.com/Microsoft/typed-rest-client
这篇关于Node.js Express中的HTTP GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!