多个 http get 请求 node.js
multiple http get request node.js
这是我的代码对于单个 http get 请求的样子。我想要做的是再调用两个 http get 请求并存储它们的结果,以便我可以适当地呈现。谁能建议我如何实现它?谢谢
router.get('/get_all_posts', function(req, res){
var body ='';
var options = {
host: 'localhost',
path: '/some_endpoint',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var request = http.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function (data_chunk) {
body += data_chunk;
});
response.on('end', function () {
if(response) {
res.render("something");
}
else
{
res.render('error', {error: {status:400,stack:body}});
}
});
});
request.end();
});
您不应该发出 http 请求。 /some_endpoint
的任何代码都将其转换为一个函数,然后在路由器内部为 /some_endpoint
和 /get_all_posts
.
调用该函数
希望对您有所帮助。
这对我有用。
async.map([options1, options2, options3], reqCall, function(err, results){
if ( err){
// do something
} else {
results[0]//first call
results[1]//second call
results[2] //third call
}
这是我的代码对于单个 http get 请求的样子。我想要做的是再调用两个 http get 请求并存储它们的结果,以便我可以适当地呈现。谁能建议我如何实现它?谢谢
router.get('/get_all_posts', function(req, res){
var body ='';
var options = {
host: 'localhost',
path: '/some_endpoint',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var request = http.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function (data_chunk) {
body += data_chunk;
});
response.on('end', function () {
if(response) {
res.render("something");
}
else
{
res.render('error', {error: {status:400,stack:body}});
}
});
});
request.end();
});
您不应该发出 http 请求。 /some_endpoint
的任何代码都将其转换为一个函数,然后在路由器内部为 /some_endpoint
和 /get_all_posts
.
希望对您有所帮助。
这对我有用。
async.map([options1, options2, options3], reqCall, function(err, results){
if ( err){
// do something
} else {
results[0]//first call
results[1]//second call
results[2] //third call
}