NODEJS -从另一个端点调用一个端点会落入CATCH,即使它成功完成



我有这两个端点(它是简化的,但思想/问题保持不变)…

/api/v1/更新

exports.update = (req, res) => {
Data.update({salary: 1})
.then(data => {
console.log("All good")
return res.status(200).send({message: "OK"})
})
.catch(error => {
console.log("Oh Crap!")
return res.status(400).send(error)
})
}

/api/v1/过程作为处理的一部分,我将第一个称为

exports.process = (req, res) => {
axios.get('http://localhost:8008/api/v1/update')
.then(data => {
console.log("You got it")
return res.status(200).send(data)
})
.catch(error => {
console.log("Not working!")
return res.status(400).send(error)
})
}

这是我在控制台得到的结果:

$>: nodemon server.js
Server running on port 8008
All good
Not working!

为什么axios调用成功("update";

我错过了什么?

编辑:

好吧,我明白了…错误在/api/v1/process的return res.status(200).send(data)

错误:将循环结构转换为JSON

所以我所做的是提取值(第一个端点的响应->更新)并发送它之后:)它现在工作得很好…愚蠢的错误

facepalm指

返回/api/v1/process的res.status(200).send(data)时出错

错误:将循环结构转换为JSON

所以我所做的是提取值(第一个端点的响应->更新)并发送它之后:)它现在工作得很好…愚蠢的错误

我认为问题是控制器返回未定义,只有在执行之后,它才试图返回并执行res.send。对于这种问题,我使用async/await来简化异步调用


exports.update = async (req, res) => {
try {
await Data.update({salary: 1});
res.status(200).send({message: "OK"});
} catch(error) {
console.log("Oh Crap!")
res.status(400).send(error)
}
}

还可以查看axios:

中的错误详细信息。
.catch(error => {
console.log("Not working!", error);
return res.status(400).send(error);
})

最新更新