Setting authorization header in Fetch API

Rowland picture Rowland · Aug 6, 2017 · Viewed 67.6k times · Source

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.

Answer

Pankaj Bhardwaj picture Pankaj Bhardwaj · Feb 23, 2018
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
    }));