Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I am making a small social network application. I came up with a like post route and the user has to be logged in to be able to perform that action, and I have auth middleware that looks like this:

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');
  }
};

When I pass an object with an authorization token to Axios, I get an error, here is the action.js file:

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 },
    });
  }
};

When I open the network tab in the browser, the request tab shows that I forward the headers {Authorization: Bearer …. token} and in response I get error 401.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m no expert with Axios, but according to the documentation, the put method uses data as the second argument and config as the third.

Maybe try to provide an empty value like null or an empty string for the second argument:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading