这是一个测试程序,因为我正在学习使用JSON和令牌。终点是Python Flask。它似乎工作得很好,甚至它在我的页面中显示的内容也很好,只有我在控制台中看到错误。
代码:
function encodeUser(user, password) {
var token = user + ":" + password;
var hash = btoa(token);
return "Basic " + hash;
}
function login(resultElement) {
result = document.getElementById(resultElement)
u = document.getElementById("email").value;
p = document.getElementById("password").value;
let xhr = new XMLHttpRequest();
let url = config_baseurl + "/login"
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Authorization", encodeUser(u, p));
xhr.onreadystatechange = function() {
txt = this.responseText;
respJson = JSON.parse(txt);
result.innerHTML = 'response: ' + txt + '<br><br>token: ' + respJson.token;
};
xhr.send();
}
结果显示在我的页面:
响应:{"token": " eyjwdwjsawnfawqioii3dixmdvjni00zwrhltqymjmtymq2yy1hmdhmmzgznwexzmuilcjlehaioje2mzq5mja4ndr9 . ihjqf3qgojlwcsuw - ittk - iiruguanmtnkyuxbdni0y;}
标记:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwdWJsaWNfaWQiOiI3ODIxMDVjNi00ZWRhLTQyMjMtYmQ2Yy1hMDhmMzgzNWExZmUiLCJleHAiOjE2MzQ5MjA4NDR9.iHJQf3qGOJlWcSuw-itTk-IirUGUAnmtNKyUXBDnI0Y
控制台显示此错误
Uncaught SyntaxError: JSON输入的意外结束在JSON。parse ()at XMLHttpRequest.xhr.onreadystatechange (example.js:36)
你可以试试fetch/promises吗?使用XMLHttpRequest计时是很困难的。我怀疑responseText在解码JSON时实际上没有值
像这样
function encodeUser(user, password) {
const token = user + ":" + password;
const encoded = btoa(token); // NOTE: Base64 is not hashing!
return "Basic " + encoded;
}
function login(resultElement) {
const result = document.getElementById(resultElement);
const u = document.getElementById("email").value;
const p = document.getElementById("password").value;
const url = config_baseurl + "/login";
const init = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: encodeUser(u, p),
},
};
fetch(url, init)
.then(res => res.json())
.then(data => {
console.log({ data });
result.innerText = data.token;
})
.catch(console.error);
}