Search code examples
reactjsexpressaxiosjwtpassport-jwt

Post Request from axios always returns Unauthorized despite having valid JWT set in header/Axios Deletes Headers


I set up passport-local to login a user, and then once logged in, the user will be given a JWT token through passport-JWT. The JWTStrategy is set up to use jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken() so that the JWT can sent with the Authorization header Authorization: `Token ${userContext.token}`}. In my react client side, I have set up a GET request using axios as shown here:

const fetchProfileDetails = async(config)=>{
    const res = await axios.get("http://localhost:8080/users/me", config)
}

    const config = {
        method:"GET",
        withCredentials: true,
        headers: {Authorization: `Bearer ${userContext.token}`}
    }

This request successfully authenticates and returns the user data from /me.

Now heres the kicker: when I use the exact same request structure, but switch the method to post in the axios request and in my express route in the backend, the request always responds with a 401 Unauthorized.

However, when I send the same request from POSTMAN, with the same Bearer Token used in the request that was Unauthorized, the request succeeds without any errors.

TLDR: GET requests work with the JWT token and return with a 200 status code, while the same request with a POST method returns with a 401 status code.

What am I missing here??!


Solution

  • I have come upon a solution for this issue. For some reason, axios was not maintaining the Authorization header I had set in my config variable, and deleted it upon making the request. To solve this, I just had to reshuffle my axios request to look like this:

    const res = await axios({
        method:'POST',
        url:"http://localhost:8080/users/test",
        headers:{'Authorization':`Bearer${token}`
      
      }})
    

    I feel cheated as I spent a ton of time on this and the solution was so underwhelming. Axios was trolling me the whole time :/