Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native fetch and basic authentication

Tags:

react-native

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

like image 959
Paul Avatar asked Jan 15 '16 16:01

Paul


People also ask

How do I use fetch with basic authentication?

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.

Is fetch available in React Native?

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.

How do I pass authorization in Fetch?

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.

How fetch data from API in React Native?

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.


2 Answers

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();
`
like image 170
Paul Avatar answered Oct 28 '22 09:10

Paul


You could have used btoa() instead of using the base_64 module. btoa() is a function on the Window.

like image 44
Dan Avatar answered Oct 28 '22 09:10

Dan