javascript – 使用fetch进行基本身份验证?
作者:互联网
我想用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();
function parseJSON(response) {
return response.json()
}
解决方法:
您缺少Basic和编码的用户名和密码之间的空格.
headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));
标签:fetch-api,javascript 来源: https://codeday.me/bug/20190926/1821107.html