我有一些 json 数据,我已经使用 $.ajax 将其发布到 API,但我想更新它以使用 fetch API。但是,我似乎设置了 Fetch API 请求,最终返回 403,所以我一定是遗漏了一些东西,但我无法解决。
Ajax 请求:
$.ajax({
type: 'POST',
url: url,
data: {
'title': data.title,
'body': data.body,
'csrfmiddlewaretoken': csrf_token,
'request_json': true
},
success: function (data) {
console.log(data)
}
});
获取尝试(多次之一):
let payload = {
'title': data.title,
'body': data.body,
'csrfmiddlewaretoken': csrf_token,
'request_json': true
}
let request = new Request(url, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify( payload )
});
fetch(request)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
})
.then((response) => response.json())
我尝试使用各种不同的 header 、内容编码并将数据作为表单数据发送:
let form_data = new FormData();
form_data.append( "json", JSON.stringify( payload ) );
let request = new Request(url, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: form_data
});
...
任何帮助都会很棒,如果您需要更多信息,请告诉我
谢谢
最佳答案
要将现有的 jQuery.ajax
请求移植到 fetch,您需要考虑到 jQuery 始终包含您的 cookie,但 fetch
不会。
Quoting MDN (强调我的):
Note that the fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:
- The Promise returned from fetch() won’t reject on HTTP error status [ ... ]
- By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials header must be sent).
编辑:从那时起规范已经改变,所以这应该不再是一个问题:
Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.
因此以下内容(返回原始答案)仅适用于“旧版”浏览器。
感谢 David Richmond 的评论:)
所以你得到 403 (Forbidden)因为您的 API 可能依赖于 cookie 进行身份验证/授权(即使在您发送 csrfmiddlewaretoken
的情况下,服务器端框架可能仍然需要一个带有它的 cookie——猜 Django?)。
要解决此问题,add credentials: "same-origin"
to your Request
(*),像这样:
let request = new Request(url, {
method: 'post',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
(*) credentials
的有效选项是:
omit
:从不发送 cookie。这是默认设置(也是您的问题)。同源
:仅当 URL 与调用脚本同源时才发送 cookie。include
:始终发送 cookie,即使是跨源调用也是如此。
关于javascript - 将 jquery ajax POST 请求更改为获取 api POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429145/