我有一个带有多个 api 端点的节点 Web 服务器。其中一个端点需要向另一台服务器发出请求以组合其自己的响应。我已经看到了一些不同的答案,其中包含指向允许纯同步 Web 请求的库的链接,但它们都与警告说不要在生产中使用它们相关联。
这是我的服务器请求处理程序的示例:
app.get('/my_api_endpoint', function (req, res) {
// Need to get data from other webservice using data
// from this request.
data = request_to_other_web_service(req.params.some_value);
res.status(200);
res.send("This is the " + data);
res.end();
});
是否有处理此类请求的标准模式?
尝试同步调用 HTTP 请求时收到错误/警告的原因是,从一开始,node.js 就是用回调和事件循环的核心理念构建的。如果您尝试以同步方式编写异步代码......我可以为您指出 async/await 的方向。你可以用npm install node-fetch
const fetch = require('node-fetch');
app.get('/my_api_endpoint', async function (req, res) {
// Need to get data from other webservice using data
// from this request.
data = await fetch("http://...");
res.status(200);
res.send("This is the " + data);
res.end();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句