Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting authorization header in Fetch API

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.

like image 762
Rowland Avatar asked Aug 06 '17 19:08

Rowland


People also ask

How do I add Authorization header to fetch?

To use an authorization header with fetch in React Native, we set the headers option when we call fetch . fetch(url, { method: "post", headers: new Headers({ Authorization: "Basic " + btoa("username:password"), "Content-Type": "application/x-www-form-urlencoded", }), body: "foo=1&bar=2", });

How do I pass Authorization bearer in header?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.


2 Answers

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     })); 
like image 190
Pankaj Bhardwaj Avatar answered Sep 18 '22 00:09

Pankaj Bhardwaj


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) }); 
like image 43
Fabian Schultz Avatar answered Sep 18 '22 00:09

Fabian Schultz