javascript - 如何在前端使用 AJAX (jquery) 警告从快速后端获取的错误
问题描述
当从 express 后端服务器接收数据并对其进行操作时,success 函数工作得非常好。我无法正确处理后端抛出的错误。可以获取状态码(400 或其他)和相关文本(错误请求等),但不能获取 express 后端发送的实际消息。
后台登录代码
router.post("/users/login", async (req, res) => {
try {
const user = await User.findByCredentails(
req.body.email,
req.body.password
);
const token = await user.generateAuthToken();
res.send({ user, token });
} catch (error) {
res.status(400).json({ error: error.message }); //error.message is thrown by the database (which logs perfectly fine in the backend when some error occurs)
}
});
发送消息的数据库代码(这里没有错误;放在这里仅供参考)
userSchema.statics.findByCredentails = async (email, password) => {
const user = await User.findOne({ email });
if (!user) throw new Error("Unable to find a user with the entered email");
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) throw new Error("Incorrect password, try again");
return user;
};
前端代码(成功但不会出错)
function login() {
const data = {
email: $("#email-field").val(),
password: $("#password-field").val()
};
$.ajax({
url: "/users/login",
method: "POST",
data,
success: function(userData) {
console.log(userData); //works just fine
},
error: function(jqXHR) {
//how can I get that error message here. I'm able to get jqXHR.status and .textStatus but not the actual message that I want.
}
});
}
解决方案
推荐阅读
- python - 将 -profile 参数添加到 python selenium 选项时,Firefox 连接被拒绝
- angular - 新浏览器选项卡中的 Angular 应用程序不起作用
- java - 一个 Java 项目出错,而另一个运行没有错误
- rust - 如何解决 NLL 限制“不能借用 `*
` 一次多次可变" 在一个循环中? - sql - 根据变量返回不以数字结尾的值
- pdf - 使用 Inkscape(命令行)将 SVG 导出为 PDF 时更改 DPI
- azure - 如何访问安装在 Azure 中运行的托管 k8 上的 ingress-nginx 命名空间中的 Prometheus 和 Grafana?
- c++ - 如何在开始时停止程序以便将 GDB 附加到该程序?
- vim - 如何在 neovim 终端中禁用行号?
- r - Plotly R:使用颜色和转换线图