Cihan Özcan
Cihan Özcan

Reputation: 103

How to set token in headers axios

I am making post request with axios and these are my codes.

//Helper function
export const postDataApi = async (url, post, token) => {
  const res = await axios.post(`/api/${url}`, post, {
    headers: { Authorization: `Bearer: ${token}` },
  });

  return res;
};

 // Sending request
 const res = await api.postDataApi("auth/register", data, token);
 console.log(res);

After sending the request, I take my access token in server side but in the res.data.

enter image description here

But when we look at config.headers we see that token is undefined

enter image description here

It is because my helper function postDataApi can't see the token parameter since it makes its functionality before the sending request.

When using Postman, I could easily set the token manually but I don't know how to do it in React.js by using axios.

When I researched I found that I should use axios.defaults.headers.postbut becuase I am beginner I couldn't handle it

How can I set my token in config/headers ?

This is the server side

 return res.status(201).json({
      success: true,
      accessToken,
      newUser,
 });

Upvotes: 0

Views: 2550

Answers (2)

Pankaj
Pankaj

Reputation: 581

As others have mentioned that you are not passing the token correctly while making the API call.

So, instead of passing token to every API call, you can think of it storing somewhere locally like in the Local Storage or in Cookies, and try to access it in the following manner:

export const postDataApi = async (url, post) => {
    const config = {
        headers: {
            "Content-type": "application/json",
              "Authorization": `Bearer ${Cookies.get("jwt")}`,
        },
    };
    const res = await axios.post(`/api/${url}`, post, config);
}

Another way to do this properly is to use Axios Interceptors

Upvotes: 1

Sachin Ananthakumar
Sachin Ananthakumar

Reputation: 810

const res = await api.postDataApi("auth/register", data, token); // Pass the token
 console.log(res);

if you want to set the headers for every request you can use this

axios.defaults.headers.common['Authorization'] = 'token';

Upvotes: 0

Related Questions