Setting authorization header in Fetch API Setting authorization header in Fetch API express express

Setting authorization header in Fetch API


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    }));


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.jsconst 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) });


You can pass headers as second parameter of fetch:

fetch(<your url>, {  headers: {     authorization: <whatever is needed here>   }})