为什么 fetch 请求会导致服务器返回 403,而 XMLHttpRequest 不会?



我使用以下代码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();

但是,我想在我的代码中使用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);
});

我想知道两者之间的区别以及我应该修改什么以使fetch工作。

如果服务器端有凭据验证,那么它可能会失败,因为 fetch 不发送或接收 cookie。你必须做 -

credentials:'include'

在您的获取请求中,根据 Fetch 上的 Mozilla 文档

默认情况下,fetch 不会从服务器发送或接收任何 cookie, 如果站点依赖于 维护用户会话(要发送 Cookie,凭据标头 必须发送)。

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

最新更新