【问题标题】:How to send error messages from express to react/redux如何将错误消息从 express 发送到 react/redux
【发布时间】:2021-07-18 06:53:18
【问题描述】:

我有一个使用 redux 的 MERN 应用程序。我的操作如下所示:

export const logIn = (logInData) => async (dispatch) => {
  try {
    const { data } = await api.logIn(logInData);
    localStorage.setItem('auth', JSON.stringify(data))
    dispatch({
      type: LOG_IN,
      payload: data
    });
  } catch (error) {
    dispatch({
      type: ADD_FLASH_MESSAGE,
      payload: error
    })
  }
}

我的服务器看起来像这样

export const logIn = async (req, res) => {
  const logInParams = req.body;

  const user = await User.findOne({ email: logInParams.email });
  if (!user) {
    console.log("USER NOT FOUND");
    res.status(400).json({
      message: "Invalid credentials."
    });
  }

  const passwordMatches = await bcrypt.compare(logInParams.password, user.password);

  if (!passwordMatches) {
    console.log("WRONG PASSWORD")
    return res.status(400).json({
      message: "Invalid credentials."
    })
  }

    // Sign in user with jwt
    const payload = {
      user: {
        id: user.id
      }
    }

    jwt.sign(payload, config.get('jwtSecret'), (error, token) => {
      if (error) throw error;
      console.log('Successfully logged in');
      return res.status(200).json({
        token: token,
        user: user,
        loggedIn: true
      });
    })
}

我无法在我的操作中访问我的错误消息。我只是收到这样的错误消息

POST http://localhost:5000/auth/login 400 (Bad Request)

我的 console.log 看起来像这样:

Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

如何从我的服务器访问我的自定义错误消息?

【问题讨论】:

    标签: reactjs express redux


    【解决方案1】:

    尝试获取error.status 的状态和error.data.message 的自定义消息

    【讨论】:

      【解决方案2】:

      您的自定义错误消息包含在 error.response.data 中 尝试在您的操作中更改此设置:

      export const logIn = (logInData) => async (dispatch) => {
      try {
         const { data } = await api.logIn(logInData);
         localStorage.setItem('auth', JSON.stringify(data))
         dispatch({
          type: LOG_IN,
          payload: data
        });
      }
       catch (error) {
          dispatch({
           type: ADD_FLASH_MESSAGE,
          payload: **error.response.data**
        })
      }
      

      }

      【讨论】:

        猜你喜欢
        • 2016-06-12
        • 2021-11-02
        • 1970-01-01
        • 2019-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-07
        • 1970-01-01
        相关资源
        最近更新 更多