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

4 Answers 4

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();
`
Sign up to request clarification or add additional context in comments.

4 Comments

Can please you share npm package name here ..!
For me, this is working only in debug mode. Did you guys any issue like this?
i am using rn-fetch-blob RNFetchBlob.base64.encode(authString)
@MaheshK, it is called base-64: npmjs.com/package/base-64
2

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

1 Comment

This is happening in React Native and btoa, at least then, was not available I think.
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>
           )}
         />

Comments

-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,
      }
    })

1 Comment

I get an error that package is missing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.