我的控制器正在使用
request
包向另一个 API 发出服务器端 HTTP 请求。我的问题是如何提出多个此类请求?这是我当前的代码:
** 更新代码 **
module.exports = function (req, res) {
var context = {};
request('http://localhost:3000/api/single_project/' + req.params.id, function (err, resp1, body) {
context.first = JSON.parse(body);
request('http://localhost:3001/api/reports/' + req.params.id, function (err, resp2, body2) {
context.second = JSON.parse(body2); //this line throws 'SyntaxError: Unexpected token u' error
res.render('../views/project', context);
});
});
};
我需要再进行两次这样的调用,并将其返回的数据发送到我的模板...
有人可以帮忙吗?
提前致谢!
function makePromise (url) {
return Promise(function(resolve, reject) {
request(url, function(err, resp, body) {
if (err) reject(err);
resolve(JSON.parse(body));
});
});
}
module.exprts = function (req, res) {
let urls = ['http://localhost:3000/api/1st',
'http://localhost:3000/api/2st',
'http://localhost:3000/api/3st'].map((url) => makePromise(url));
Promise
.all(urls)
.then(function(result) {
res.render('../views/project', {'first': result[0], 'second': result[1], 'third': result[2]});
})
.catch(function(error){
res.end(error);
});
}
您可以在最新的nodejs中使用
Promise
lib。
嵌套请求调用。这是处理请求之间的依赖关系的方法。如果需要,只需确保您的参数在整个范围内是唯一的。
module.exports = function (req, res) {
var context = {};
request('http://localhost:3000/api/1st', function (err, resp1, body) {
var context.first = JSON.parse(body);
request('http://localhost:3000/api/2nd', function (err, resp2, body) {
context.second = JSON.parse(body);
request('http://localhost:3000/api/3rd', function (err, resp3, body) {
context.third = JSON.parse(body);
res.render('../views/project', context);
});
});
});
};
如果您使用bluebird承诺库,最简单的方法:
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
module.exports = function (req, res) {
var id = req.params.id;
var urls = [
'http://localhost:3000/api/1st/' + id,
'http://localhost:3000/api/2st/' + id,
'http://localhost:3000/api/3st/' + id
];
var allRequests = urls.map(function(url) { return request(url); });
Promise.settle(allRequests)
.map(JSON.parse)
.spread(function(json1, json2, json3) {
res.render('../views/project', { json1: json1 , json2: json2, json3: json3 });
});
});
即使一个(或多个)失败,它也会执行所有请求
我在 2023 年编写了一个名为 sync-request-curl 的库,它可以帮助处理 NodeJS 中的同步请求(如果你出于某种原因想避免
async
/await
)。
它包含原始 sync-request 中的功能子集,但利用 node-libcurl 在 NodeJS 中获得更好的性能。
一个简单的HTTP GET请求可以写成如下:
import request from 'sync-request-curl';
const response = request('GET', 'https://ipinfo.io/json');
console.log('Status Code:', response.statusCode);
console.log('body:', response.body.toString());
当应用于您的用例时,生成的代码可能类似于
const request = require('sync-request-curl');
module.exports = function (req, res) {
const context = {};
const response1 = request('GET', `http://localhost:3000/api/single_project/${req.params.id}`);
if (response1.statusCode === 200) {
context.first = JSON.parse(response1.getBody('utf8'));
} else {
// handle error
}
const response2 = request('GET', `http://localhost:3001/api/reports/${req.params.id}`);
if (response2.statusCode === 200) {
context.second = JSON.parse(response2.getBody('utf8'));
} else {
// handle error
}
res.render('../views/project', context);
};
希望这有帮助:)。