我想用fetch写一个简单的基本身份验证,但我一直得到一个401错误。如果有人告诉我代码有什么问题,那就太棒了:
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();
节点用户(react, express)遵循这些步骤
NPM安装base-64
Import {encode} from "base-64";
const response = await (URL, {
方法:“文章”,
headers: new headers ({
“授权”:“基本”+编码(用户名+“:”+密码),
“内容类型”:“application / json”
}),
身体:JSON.stringify ({
:“PassengerMobile xxxxxxxxxxxx”,
“密码”:“xxxxxxx”
})
});
Const posts = await response.json();
不要忘记将整个函数定义为async
一个简单的复制粘贴到Chrome控制台的例子:
fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));
或者带着等待:
let response = await fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}});
let data = await response.json();
console.log(data);