Home > Software engineering >  I am not able to send JWT token in headers in react.js
I am not able to send JWT token in headers in react.js

Time:07-08

I am trying to send the JWT token in the headers in the Axios API call but in react.js I am not able to send it. I have tried some ways to send it in the header but on the backend, I am not able to get it. And If send the same token on postman then the backend is able to extract the token from the headers.

 const token = window.localStorage.getItem("token");
console.log("token",token) // token

const apiHeaders = {
          headers: {
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "application/json, text/plain, */*",
            "token": `${token}`,
          },
        };
        const result = await Axios.get(
          `${process.env.REACT_APP_BASE_URL}/api/student/AllProjects`,
          {
            withCredentials: true,
            headers: apiHeaders, 
          }
        );


I have also tried sending token as

 token: `${token}`
or

 token: token

I don't know what I am doing wrong here?

CodePudding user response:

I think your problem is that you have headers twice:

const apiHeaders = { headers: { ... } }

So apiHeaders is an object with a headers field.

When you use that in the get call, that gets expanded to what is effectively:

const result = await Axios.get(
          `${process.env.REACT_APP_BASE_URL}/api/student/AllProjects`,
          {
            withCredentials: true,
            headers: {
               headers: {
                 token: token
               }
            }, 
          }
        );

BTW, it would be normal to pass that as a "bearer token" in the authorization header:

headers: {
    Authorization: `Bearer ${token}`
}
  • Related