JD *_*dez 3 javascript xmlhttprequest fetch
我XMLHttpRequest使用以下代码从服务器获取了一个 json 值:
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let msg = JSON.parse(xhr.responseText);
// Send the request to our POST Servlet
}
};
xhr.open("GET", "/libs/granite/csrf/token.json", true);
xhr.send();
Run Code Online (Sandbox Code Playgroud)
但是,我想fetch在我的代码中使用,但是,在尝试下面的代码时,我立即收到了 403 错误的答复:
fetch("/libs/granite/csrf/token.json", { method: "GET" })
.then((response: any) => {
if (response.status === 200 || response.statusText === "OK") {
callback(ResponseCode.SUCCESS);
} else {
callback(ResponseCode.ERROR);
}
})
.catch((error: any) => {
callback(ResponseCode.ERROR);
});
Run Code Online (Sandbox Code Playgroud)
我想知道两者之间的区别以及我应该修改什么才能完成fetch工作。
小智 5
如果服务器端有凭据验证,那么它可能会失败,因为 fetch 不发送或接收 cookie。你必须做——
credentials:'include'
Run Code Online (Sandbox Code Playgroud)
在您的 fetch 请求中,根据 Fetch 上的 mozilla 文档
默认情况下,fetch 不会从服务器发送或接收任何 cookie,如果站点依赖于维护用户会话(要发送 cookie,必须发送凭据标头),则会导致未经身份验证的请求。
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
| 归档时间: |
|
| 查看次数: |
4021 次 |
| 最近记录: |