首页 > 解决方案 > 为什么我的 Post 请求没有返回正确的错误?

问题描述

我创建了一个服务器端请求来处理登录。该请求在邮递员中正常工作。如果我将正确的登录数据传递给它,它也可以在客户端正常工作。但是,当我尝试使用不正确的数据(例如不正确的电子邮件或密码)在客户端发出请求时,它只会返回 401 错误,而应该返回“电子邮件登录失败”或“登录失败”的消息密码失败”。但是我可以在邮递员中使用相同的错误数据提出相同的请求,它会返回正确的结果。

服务器端

router.post("/login", async (req, res) => {
  let getUser;
  // finds user via email
  await User.findOne({
    email: req.body.email,
  })
    .then((user) => {
      if (!user) {
        return res.status(401).json({
          message: "Login Failed at email",
        });
      }
      getUser = user;
      return bcrypt.compare(req.body.password, user.password);
    })
    .then((response) => {
      if (!response) {
        return res.status(401).json({
          message: "Login Failed at password",
        });
      }
    })
    .then(() => {
      let jwToken = jwt.sign(
        {
          email: getUser.email,
          userId: getUser.id,
        },
        "longer-secret-is-better",
        {
          expiresIn: "2h",
        }
      );
      res.status(200).json({
        token: jwToken,
        expiresIn: 600,
        user: getUser,
      });
    })
    .catch((err) => {
      return res.status(401).json({
        message: err.message,
      });
    });
});

客户端请求

import axios from "axios";

export const login = (userInfo) => async (dispatch) => {
  dispatch({
    type: "SET_INFO_REQUEST",
  });

  try {
    await axios({
      method: "post",
      url: "https://ecommersappbytim.herokuapp.com/auth/login",
      header: { "Content-Type": "application/json" },
      data: {
        email: userInfo.email,
        password: userInfo.password,
      },
    }).then((response) => {
      console.log(response.data);
      dispatch({
        type: "SET_INFO_SUCCESS",
        payload: response.data.user,
      });
    });
  } catch (error) {
    dispatch({
      type: "SET_INFO_FAILURE",
      error,
    });
  }
};

所以我唯一的问题是当使用 axios 在客户端传递不正确的登录数据时,它并没有给我我期望的回报

标签: expressaxios

解决方案


推荐阅读