在某些情况下,当在我的 Node/express 服务器上命中特定路由时,我想向 API 发出请求并将该响应直接返回给客户端。我关注了这个堆栈溢出帖子:Send response from server side axios request to React/Redux app
要创建这个:
router.use('/', async (req, res) => {
const apiUrl = `https://assets.scratch.mit.edu${req.url}`;
console.log(apiUrl);
const scratchResponse = await axios.get(apiUrl);
try {
res.send(scratchResponse);
console.log('worked!', apiUrl);
} catch (error) {
console.log('error in assets get request', apiUrl, error);
res.sendStatus(500);
}
});
这对于某些请求有效,但对于其他请求则中断并出现错误:
TypeError: Converting circular structure to JSON
根据此堆栈溢出帖子的建议:JSON.stringify, avoid TypeError: Converting circular structure to JSON
我尝试通过添加此导入来使用 npm flatted
库:
const { stringify } = require('flatted/cjs');
并在我的回复之前进行字符串化:
res.send(stringify(scratchResponse));
但似乎某些对客户端至关重要的信息正在被删除(客户端中断并表示缺少属性)。
是否可以直接发送我从 API 收到的响应?
最佳答案
嗯,最简单的方法可能是将响应通过管道传递给客户端:
router.get('/', (req, res) => {
axios({
method: 'get',
url: apiUrl,
responseType: 'stream'
})
.then(function(response) {
response.data.pipe(res)
});
});
如果第三方的格式有问题,你仍然不走运,但这至少会让你的服务器端处理摆脱问题,而且性能应该会好一点因为您只是通过管道传递响应而不是在服务器上获取完整响应,所以将其序列化为 JSON 只是为了将其重新发送到响应流。
关于node.js - 将 API 的响应作为 Node 服务器的响应传递会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972716/