如何防止res.send()覆盖整个文档



我正在启动一个ajax调用,用于处理将用户插入数据库的操作。

我想向ajax成功返回一个字符串或状态代码以供进一步使用。

如果我在服务器端使用res.send((,它会覆盖当前文档,并在左上角以黑色文档显示响应。

我试过使用return,但也没用,除非我做错了什么。

客户端

$.ajax({
url: "/register",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ data: data }),
success: function (response) {
console.log(response);  
Swal.fire({
title: "Success!",
text: "All good",
icon: "success",
});
},
error: function (e) {
Swal.fire({
title: "Error!",
text: "There was an error saving to the database",
icon: "error",
});
console.log(e);
},
});

服务器端

router.post("/", async (req, res) => {
req.body = sanitize(req.body);
const user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try {
await user.save();
res.status(200).send("Success");
} catch (e) {
res.status(500).send("Error");
// Implement response to the user if for some reason the save failed
}
});

我将ajax调用封装在一个函数中,该函数在任何地方都没有调用,我只是作为默认值进行常规表单提交。闭合

最新更新