Не удается прочитать свойство «undefined»: POST-запрос от React к Express

#reactjs #express #mongoose #redux #axios

#reactjs #выразить #мангуст #redux #axios

Вопрос:

У меня есть этот контроллер для аутентификации пользователя по его электронной почте и паролю

 const authUser = asyncHandler(async (req, res, next) => {
  console.log('Hit');
  const { email, password } = req.body;
  await User.findOne({ email }, async (err1, foundUser) => {
    if (err1) {
      next(err1);
    } else if (foundUser amp;amp; (await foundUser.matchPasswords(password))) {
      res.json({
        _id: foundUser._id,
        name: foundUser.name,
        email: foundUser.email,
        token: generateWebToken(foundUser._id),
      });
    } else {
      res.status(401);
      next(new Error('Invalid credentials'));
    }
  });
});

 

где метод экземпляра mongoose matchPasswords определяется как

 userSchema.methods.matchPasswords = async function (enteredPassword) {
  return await bcrypt.compare(
    enteredPassword,
    this.password,
    (err, success) => {
      console.log(success);
      return success;
    }
  );
};
 

В интерфейсе React я создал создателя действия loginUser следующим образом

 export const loginUser = ({ email, password }) => async (dispatch) => {
  try {
    dispatch({ type: USER_LOGIN_REQUEST });

    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };
    const { data } = await axios.post(
      '/api/v1/users/login',
      { email, password },
      config
    );

    dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });
  } catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response amp;amp; error.response.data.message
          ? error.response.message.data
          : error.message,
    });
  }
};
 

Однако, когда я пытаюсь войти в систему с неправильными или правильными учетными данными, я получаю это сообщение на экране и консоли Uncaught (in promise) TypeError: Cannot read property 'data' of undefined . Выше есть эта ошибка main.js?attr=bsXXNSP9r2dL_fbuBOkoev2GjgusyPgY7MC7K-twziLtf_MItBzQdXJ4l_HgsPQw:2699 POST http://localhost:3000/api/v1/users/login 401 (Unauthorized) , которая заставила меня подумать, что, возможно, это ошибка прокси, потому что мой сервер работает на порту 5000, но console.log('Hit'); внутренний authUser контроллер запускается, когда я делаю запрос, что означает, что запрос достигает серверной части, но есть какая-то неперехваченная ошибка. В чем моя ошибка?

Комментарии:

1. error.response.data.message != error.response.message.data

2. Глупый я! Спасибо @DaveNewton