在某些情况下,当在我的节点/express 服务器上命中特定路由时,我想向 API 发出请求并将该响应直接返回给客户端。我关注了这个堆栈溢出帖子:将服务器端 axios 请求的响应发送到 React/Redux 应用程序 https://stackoverflow.com/questions/46496459/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,避免 TypeError:将循环结构转换为 JSON https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json
我尝试过使用 npmflatted
通过添加此导入库:
const { stringify } = require('flatted/cjs');
并在我的回复之前进行字符串化:
res.send(stringify(scratchResponse));
但似乎某些对客户至关重要的信息正在被删除(客户中断并表示缺少属性)。
是否可以直接发送我从 API 收到的响应?