我正在通过在此API中调用另一个API来创建微服务。另一个API返回了数据,但我不断收到此错误
这是付款响应{成功:true,json:1}(节点:31709) UnhandledPromiseRejectionWarning:TypeError:转换循环 构造为JSON 在JSON.stringify() 在stringify(/Users/greatness/microservice/order/node_modules/express/lib/response.js:1119:12) 在ServerResponse.json(/Users/alpha/setel/order/node_modules/express/lib/response.js:260:14) 在router.post(/Users/alpha/setel/order/src/routes/order.js:59:21) 在 在process._tickCallback(内部/进程/next_tick.js:189:7)(节点:31709)处UnhandledPromiseRejectionWarning:未处理的承诺 拒绝。该错误是由抛出异步内部引起的 没有捕获块或拒绝承诺 未使用.catch()处理。 (拒绝ID:2)
router.post("/order", async (req, res) => {
let paymentResponse;
// Im using Mongoose
const order = new Order()
try {
// Call the payment API
paymentResponse = await axios.post('http://localhost:3002/api/v1/payment', {
order
})
} catch (err) {
res.status(500).json({
success: false,
message: err.message
})
}
console.log("This is payment Response", paymentResponse.data)
// Success change the order status to confirmed
if (paymentResponse.data.json === 0) {
order.status = "confirmed"
} else {
order.status = "declined"
}
order.save()
res.status(200).json({
success: true,
paymentResponse,
order
})
})
另一个只是返回正常的json
router.post("/v1/payment", async (req, res) => {
try {
// If 0 confirmed if 1 declined
const randomResponse = Math.round(Math.random())
res.status(200).json({
success: true,
json: randomResponse
})
} catch (err) {
res.status(500).json({
success: false,
message: err.message
})
}
})
我该怎么办?我的状态一直保持500。
致谢。
答案 0 :(得分:1)
您正在这样呼叫json
:
res.status(200).json({
success: true,
paymentResponse, <---
order
})
paymentResponse
是axios的响应对象,它不是简单的json,而是具有方法,属性和循环引用的复杂JS对象。
您想要做的是仅发送原始数据,如下所示:
res.status(200).json({
success: true,
paymentResponse: paymentResponse.data, <--- Make sure the response from payment is valid json!
order
})