19

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

Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
Paul
  • 7,157
  • 6
  • 32
  • 37

4 Answers4

40

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();
`
Paul
  • 7,157
  • 6
  • 32
  • 37
2

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

Dan
  • 8,041
  • 8
  • 41
  • 72
  • 1
    This is happening in React Native and btoa, at least then, was not available I think. – Paul Mar 30 '17 at 05:28
0

Get request with authorization for React Native Mobile application, i have spent more time searching for these lines inside fetch

 var base64 = require("base-64"); // install it before use from npm i base-64

 const uname = "some username goes here";
 const pword = "some password goes here";

const getMovies = async () => {
   try {
     const response = await fetch(
       "API URL goes here",
       {
         headers: {
           Authorization: "Basic " + base64.encode(uname + ":" + pword),
         },
       }
     );

     data = await response.json();
     setData(data);

     console.log(data);
     // console.log(data.name);
     return data;
   } catch (error) {
     console.error(error);
   } finally {
     setLoading(false);
   }
 };

 useEffect(() => {
   getMovies();
 }, []);


// other code 

// inside return
  <FlatList
           keyExtractor={(item) => item.id}
           data={data}
           renderItem={({ item }) => (
             <View style={styles.text_container}>
               <Text>{item.name}</Text>
               <Text>{item.images[0].name}</Text>
               <Text>{item.images[0].src}</Text>
             </View>
           )}
         />
fixedDrill
  • 183
  • 1
  • 13
-1

Without additional imports in React Native:

const Buffer = require("buffer").Buffer;

const credential = "Basic " + Buffer.from(email + ":" + password).toString("base64");

fetch(url, {
      headers: {
        Authorization: credential,
      }
    })
A---
  • 2,373
  • 2
  • 19
  • 25