2017-05-08 48 views
19

我想用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() 
} 
+4

如果在標題中單詞「基本」之後沒有空格,可以嗎? – Orifjon

+0

哦f ***,是啊!謝謝!完全錯過了;-) –

回答

30

你缺少Basic和編碼的用戶名和密碼之間的空間:如果有人告訴我,什麼是錯的代碼這將是真棒。

headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));