当我使用授权令牌传递 axios 配置 object 时,为什么会出现身份验证错误? MERN

Why do I get an authentication error when I pass an axios config object with an authorization token? MERN

我正在制作一个小型社交网络应用程序。我想出了一个类似 post 的路由,用户必须登录才能执行该操作,并且我有如下所示的 auth 中间件:

const auth = async (req, res, next) => {
  // check header
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer')) {
    throw new UnauthenticatedError('Authentication invalid');
  }
  const token = authHeader.split(' ')[1];

  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);

    req.user = { userId: payload.userId };
    next();
  } catch (error) {
    throw new UnauthenticatedError('Authentication invalid');
  }
};

当我将带有授权令牌的 object 传递给 Axios 时,出现错误,这是 action.js 文件:

export const likePost = id => async (dispatch, getState) => {
  try {
    const {
      userLogin: { userInfo },
    } = getState();

    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    const { data } = await axios.put(`/api/v1/post/${id}/like`, config);

    dispatch({ type: POST_LIKE_SUCCESS, payload: data });
  } catch (error) {
    console.log(error);
    dispatch({
      type: POST_LIKE_FAIL,
      payload: { msg: error.response.data.msg },
    });
  }
};

当我在浏览器中打开网络选项卡时,请求选项卡显示我转发了 headers {Authorization: Bearer .... token} 作为响应,我收到错误 401。

我不是 Axios 专家,但是 according to the documentationput 方法使用 data 作为第二个参数,config 作为第三个参数。

也许尝试为第二个参数提供空值,如 null 或空字符串:

const { data } = await axios.put(`/api/v1/post/${id}/like`, null, config);