首页 > 解决方案 > 如何在前端使用 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.
          }
        });
      }

标签: javascriptjqueryajaxmongodbexpress

解决方案


推荐阅读