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.
CodePudding user response:
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);