Sometimes, we want to use an authorization header with fetch in React Native.
In this article, we’ll look at how to use an authorization header with fetch in React Native.
How to use an authorization header with fetch in React Native?
To use an authorization header with fetch in React Native, we set the headers
option when we call fetch
.
For instance, we write
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 call fetch
with an object with some request options to make a request.
In the object we set the request method
to 'post'
.
And we set the headers
to a Headers
object to set the request headers.
In the object we pass into Headres
, we set the Authorization
header by setting the Authorization
property.
And we set the Content-Type
header the same way.
We set the body
to the request body.
Conclusion
To use an authorization header with fetch in React Native, we set the headers
option when we call fetch
.