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.
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", });
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.
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.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) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With