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