【发布时间】:2022-01-16 13:19:01
【问题描述】:
我正在触发一个处理将用户插入数据库的 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 是在表单提交中完成的吗?这些症状对于 ajax 请求没有意义。显示的路线也没有
send() -
抱歉,这是我尝试的最新方法。我将问题更新为我最初尝试的内容。是的,提交按钮调用一个 js 函数,该函数执行一些输入验证并提交文档。
-
所以问题很可能是您没有阻止默认表单提交并且页面正在重新加载。向我们展示提交代码,您能确认页面重新加载吗?
标签: javascript ajax express