【发布时间】:2018-07-26 00:31:08
【问题描述】:
我正在使用 node.js 后端,但在错误处理方面遇到了一些问题。
在后端,我使用 express 进行路由。我从前端收到一个 ajax 帖子,其中包含一个数组和一些数据。此数据应保存在数据库中。如果通过将数据添加到数据库中出现错误,我会在后端收到错误消息,但我也想向前端发送一条消息。我一直在尝试错误,但在前端我总是得到“成功”。 这是我到现在为止的代码。
后端:
router.post('/tagging', function(req, res) {
var taggedData = req.body;
var actions = taggedData.map(element => {
addTaggedData.addTaggedData(element)
.then(function(result) {
return result;
})
.catch(function(err) {
if (err.code == "ER_NO_SUCH_TABLE") {
console.log("Tagged data contains unknown project name");
res.send("ER_NO_SUCH_TABLE");
} else {
res.send(err);
}
})
});
Promise.all(actions)
.then(
res.send("Successful")
)
.catch(function(err) {
if (err.code == "ER_NO_SUCH_TABLE") {
console.log("Tagged data contains unknown project name");
res.send("ER_NO_SUCH_TABLE");
} else {
res.send(err);
}
});
})
前端ajax调用:
function postTaggedData(taggedData) {
$.ajax({
url: server_connection.url + '/tagging',
type: 'POST',
encoding: "UTF-8",
contentType: 'application/json',
data: JSON.stringify(taggedData),
success: function(data) {
if (data === "Successful") {
console.log("Tagged Data successfully send to server");
}else if(data == "ER_NO_SUCH_TABLE"){
alert("Unknown project");
} else {
alert(data);
}
},
error: function(xhr, status, error) {
if(error == "Internal Server Error"){
alert("There is an error with the server");
}else if(error == "ER_NO_SUCH_TABLE"){
alert("Unknown project");
}else{
alert("There was an error while sending the Tagged Data to the server");
console.log(xhr, "Status: ", status, error);
}
}
})
}
【问题讨论】:
-
在 addTaggedData.addTaggedData(element) 之前缺少返回语句
标签: node.js ajax error-handling promise