我想在 TypeScript 中创建 XHR。我想要访问的 API 具有以下 url:
https://my-url/user/login
传递数据时应该如下所示:
https://my-url/user/login?username=username&password=password&api_key=key
我的问题是,我使用 https://my-url/user/login
- url 形成了我的 XHR,并且在传递数据时我收到了 404 (我猜是因为他形成了这样的形式)这个https://my-url/user/login/username=username...
)。我的解决方法:将 header 直接传递到带有插入元素的异或中:
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://my-url/user/login?username=" + username
+ "&password=" + password + "&api_key=key", true);
xhr.setRequestHeader("Accept", "application/json");
// xhr.setRequestHeader("api_key", "key");
//xhr.setRequestHeader("username", username);
// xhr.setRequestHeader("password", password);
xhr.onreadystatechange = function() {
console.log("state changed - new state: " + xhr.readyState + " and Status: " + xhr.status);
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("login Request successful: " + xhr.responseText);
alert("Logged in!");
} else {
alert("Login failed!");
console.log("Error: " + xhr.status + " Message: " + xhr.statusText);
}
}
};
xhr.send();
但我不想使用这种方式,因为必须有一种方法以不同的方式执行此请求 - 有人可以给我提示如何解决这个问题吗?
最佳答案
首先,不要在请求中放置普通变量。使用encodeURIComponent
(引用:Mozilla Developer)
您可以使用此函数正确格式化 GET 参数。
function formatParams( params ){
return "?" + Object.keys(params).map((key) => {
return `${key}=${encodeURIComponent(params[key])}`
}).join("&")
}
然后你可以像这样使用它:
let xhr = new XMLHttpRequest();
xhr.open("GET", `https://my-url/user/login${formatParams({username, password, api_key: key})}`, true);
xhr.setRequestHeader("Accept", "application/json");
关于javascript - 调整 XHR header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45798202/