【发布时间】:2022-01-08 07:58:10
【问题描述】:
我知道之前有人询问过此错误消息,但我认为其他解决方案不适合我。
我正在尝试构建一个后端快速服务器来处理 React 应用程序的 API 调用。我编写了一个getData() 函数来执行此操作,app.post() 使用它来将其发送到前端。
只有在使用 res.send() 时才会弹出错误,例如我的 API 调用有效,只是在发送时中断。
以下是相关代码:
const getData = async route => {
const config = {
headers: {
'Authorization': `Bearer ${TOKEN}`,
'Content-Type': 'application/json;charset=utf-8'
}
}
let corrRoute = route[0] == '/' ? route : '/' + route
return await axios(`${URL}${corrRoute}?api_key=${API_KEY}`, config)
}
app.post('/api', async (req, res) => {
let { route } = req.body
res.send(await getData(route))
})
如果我用console.log 替换最后的res.send,它的打印效果非常好。错误是在服务器的 index.js 文件中产生的,而不是在 React 应用程序中。
这是完整的错误文本:
[server] (node:9680) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
[server] --> starting at object with constructor 'ClientRequest'
[server] | property 'socket' -> object with constructor 'TLSSocket'
[server] --- property '_httpMessage' closes the circle
[server] at JSON.stringify (<anonymous>)
【问题讨论】:
-
你不能发送
Promise作为回应。 -
我是在发送承诺吗?我认为
await确保我会发送实际的 API 数据。当我console.log(await getData(route))它返回正确的数据对象,而不是像Promise <promise> -
await getData(route).then(data => res.send(data))产生同样的错误
标签: javascript node.js express axios