I tried to use fetch with this syntax:
fetch("https://user:password@url", {
...
}).then((response) => {
...
}).done();
The same url works in CURL but returns 401 in React Native.
Any ideas?
Thanks, Paul
To use basic authentication with Fetch, all you need is a little Base64 encoding and the Authorization header. Try changing the login and password below; values other than “user” and “passwd” will result in a 401 error. Learn new data visualization techniques. Perform complex data analysis.
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
You can pass HTTP headers to the fetch() request as the second parameter. For example, to pass the Bearer Token Authorization Header, call fetch() with the {headers: {Authentication: 'Bearer Token'}} parameter. The example below shows how to send multiple headers to the server, including a custom HTTP header.
1. fetch method: The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
I found that this format https://user:password@url
works well in CURL and node but not with fetch.
I had to use base-64
npm module and pass through a Headers object.
// https://www.npmjs.com/package/base-64
const base64 = require('base-64');
...
var headers = new Headers();
headers.append("Authorization", "Basic " + base64.encode("user:password"));
fetch("https://url", {
headers: headers
})
.then((response) => { ... })
.done();
`
You could have used btoa()
instead of using the base_64
module. btoa()
is a function on the Window
.
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