Home > database >  Get authorization token from headers into fetch reactj
Get authorization token from headers into fetch reactj

Time:12-30

I am using fetch in my react project to fetch data from an API which is authenticated using a token and my login end-point in the postman return the token in authorization header, you can see enter image description here

and this's my login funtion in reactjs project

 async login(dataLogin) {

  const response = await fetch(`${API_URL}/login`, {
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    body: dataLogin
  });
  
  const data = await response
  
  console.log(response.headers);
   console.log(response.headers.Authorization);
   console.log(response.headers.get('Authorization'));

  return data;} 

enter image description here you can see that response.headers.authorization return undefined and

response.headers.get('Authorization') return null.

please anyone know how to get the authorization token from the headers?

CodePudding user response:

When you are trying to login using API, then you should receive data i.e. Authorization token or anything else in the response of call.

Check what is the response you're getting when you called an API, it should probably be like response.data First you need to check the same in Postman.

CodePudding user response:

To access value of response header server must return header name in Access-Control-Expose-Headers header. Without it Authorization is inaccessible in browser.

CodePudding user response:

response.headers.get('Authorization')
  • Related