56

I have a Node/Express backend and I'm consuming the API with a React Client. I want to be able to set the authorization header after a user is signed up. This ensures that subsequent requests are sent with the authorization header.

I can see how it's done in Axios here and how to retrieve the authorization header in Fetch here

Is it possible to do this with Fetch API and how?

Thank you in advance.

Rowland
  • 1,728
  • 1
  • 12
  • 19

5 Answers5

88
var url = "https://yourUrl";
var bearer = 'Bearer ' + bearer_token;
fetch(url, {
        method: 'GET',
        withCredentials: true,
        credentials: 'include',
        headers: {
            'Authorization': bearer,
            'X-FP-API-KEY': 'iphone', //it can be iPhone or your any other attribute
            'Content-Type': 'application/json'
        }
    }).then(responseJson => {
        var items = JSON.parse(responseJson._bodyInit);
    })
    .catch(error => this.setState({
        isLoading: false,
        message: 'Something bad happened ' + error
    }));
Pankaj Bhardwaj
  • 2,081
  • 1
  • 17
  • 37
18

As far as I know, there's no way to use default options/headers with fetch. You can use this third party library to get it to work, or set up some default options that you then use with every request:

// defaultOptions.js
const defaultOptions = {
  headers: {
    'Authorization': getTokenFromStore(),
  },
};

export default defaultOptions;

Then use the default options like:

import defaultOptions from './defaultOptions';

// With default options:
fetch('/auth', defaultOptions);

// With additional (non-default) options:
fetch('/auth', { ...defaultOptions, body: JSON.stringify(additionalData) });
Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56
  • 1
    Thank you. I use all of that but I think there should be a way to set authorization header with Fetch API. The issue is not making a request with it but setting it after authenticating the user such that in my **network** panel in the dev tool, for instance, I can see it set like other things. – Rowland Aug 06 '17 at 22:23
6

You can pass headers as second parameter of fetch:

fetch(<your url>, {
  headers: {
     authorization: <whatever is needed here>
   }
})
Dario
  • 6,152
  • 9
  • 39
  • 50
  • want to pass all the values such as : Consumer Key: value Consumer Secret: value Access Token: value Access Token Secret: value – Ankita Singh Aug 20 '18 at 05:40
  • you can add those as keys to `headers` object: `{ authorization: , 'consumer key': , 'consumer secret': , 'Access Token': , 'Access token secret': } ` – Dario Aug 20 '18 at 08:17
  • This does not work. It throw error: "Response to preflight request doesn't pass access control check: It does not have HTTP ok status" – strix25 Mar 03 '23 at 12:14
5
   headers: {
      'Authorization': `Bearer ${localStorage.getItem("token")}`,
      'Accept': 'application/json',
       'Content-Type': 'multipart/form-data;
  },
bechir majri
  • 51
  • 1
  • 2
0

In my case, the problem was that the string I was setting as the Authorization was not yet generated. I had to wrap it in a promise, and suddenly it worked.

let authHeader: string = await SearchAuthService.getAuthHeader();

Grzegorz Smulko
  • 2,525
  • 1
  • 29
  • 42