admin管理员组文章数量:1128272
I want to write a simple basic authentication with fetch, but I keep getting a 401 error. It would be awesome if someone tells me what's wrong with the code:
let base64 = require('base-64');
let url = '';
let username = 'user';
let password = 'passwd';
let headers = new Headers();
//headers.append('Content-Type', 'text/json');
headers.append('Authorization', 'Basic' + base64.encode(username + ":" + password));
fetch(url, {method:'GET',
headers: headers,
//credentials: 'user:passwd'
})
.then(response => response.json())
.then(json => console.log(json));
//.done();
I want to write a simple basic authentication with fetch, but I keep getting a 401 error. It would be awesome if someone tells me what's wrong with the code:
let base64 = require('base-64');
let url = 'http://eu.httpbin.org/basic-auth/user/passwd';
let username = 'user';
let password = 'passwd';
let headers = new Headers();
//headers.append('Content-Type', 'text/json');
headers.append('Authorization', 'Basic' + base64.encode(username + ":" + password));
fetch(url, {method:'GET',
headers: headers,
//credentials: 'user:passwd'
})
.then(response => response.json())
.then(json => console.log(json));
//.done();
Share
Improve this question
edited Jun 4, 2021 at 7:34
Tobias Buschor
3,2752 gold badges23 silver badges23 bronze badges
asked May 8, 2017 at 8:14
daniel.lozynskidaniel.lozynski
16.5k6 gold badges19 silver badges21 bronze badges
0
9 Answers
Reset to default 305A solution without dependencies.
Node
headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));
Browser
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
You are missing a space between Basic
and the encoded username and password.
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
In pure JavaScript you can also use btoa instead of base64.encode()
:
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
Note that this will only work with ASCII characters.
If you have to handle different encodings, see the linked btoa
documentation.
A simple example for copy-pasting into Chrome console:
fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));
or with await
:
let response = await fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}});
let data = await response.json();
console.log(data);
If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then:
fetch(url, {
credentials: 'include',
}).then(...);
NODE USERS (REACT,EXPRESS) FOLLOW THESE STEPS
npm install base-64 --save
import { encode } from "base-64";
const response = await fetch(URL, { method: 'post', headers: new Headers({ 'Authorization': 'Basic ' + encode(username + ":" + password), 'Content-Type': 'application/json' }), body: JSON.stringify({ "PassengerMobile": "xxxxxxxxxxxx", "Password": "xxxxxxx" }) }); const posts = await response.json();
Don't forget to define this whole function as
async
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>
)}
/>
I'll share a code which has Basic Auth Header form data request body,
let username = 'test-name';
let password = 'EbQZB37gbS2yEsfs';
let formdata = new FormData();
let headers = new Headers();
formdata.append('grant_type','password');
formdata.append('username','testname');
formdata.append('password','qawsedrf');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch('https://www.example.com/token.php', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
This is not directly related to the initial issue, but probably will help somebody.
I faced same issue when was trying to send similar request using domain account. So mine issue was in not escaped character in login name.
Bad example:
'ABC\username'
Good example:
'ABC\\username'
本文标签: javascriptBasic authentication with fetchStack Overflow
版权声明:本文标题:javascript - Basic authentication with fetch? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736719184a1949371.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论