将jquery ajax POST请求更改为fetch api POST [英] Change a jquery ajax POST request into a fetch api POST
问题描述
我有一些使用$ .ajax发布到API的json数据,但我想对其进行更新以使用fetch API.但是我似乎已经设置好Fetch API请求,最终返回了403,因此我必须丢失某些东西,但无法解决.
I have some json data that I have been posting to an API using $.ajax but I would like to update this to use the fetch API. However I seem to have it setup the Fetch API request ends up returning a 403 so I must be missing something but I can't work it out.
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)
}
});
获取尝试(众多尝试之一):
Fetch attempt (one of many):
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())
我尝试使用各种不同的标题,内容编码并使用以下形式将数据作为表单数据发送:
I have tried with various different headers, content encoding and sending the data as form data using:
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
});
...
任何帮助都会很棒,如果您需要更多信息,请告诉我
Any help would be great and if you need any more info let me know
谢谢
推荐答案
要移植现有的jQuery.ajax
请求以进行提取,您需要考虑到jQuery始终为您提供cookie,而fetch
则没有.
To port an existing jQuery.ajax
request to fetch, you need to consider that jQuery always includes cookies for you, but fetch
does not.
引用MDN (重点是我):
请注意,获取规范与jQuery.ajax()的主要区别在于两个方面:
-从fetch()返回的Promise不会因HTTP错误状态[...]
而拒绝 -默认情况下,获取操作不会从服务器发送或接收任何Cookie ,如果站点依赖于维护用户会话,则会导致未经身份验证的请求(要发送Cookie,凭据标头必须为已发送).
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).
此后规格已更改,因此这不再是问题:
spec has changed since then, so this should no longer be a problem:
自2017年8月25日起.该规范将默认凭据策略更改为同源.自61.0b13起,Firefox发生了更改.
因此,以下内容(返回原始答案)仅适用于较旧的"浏览器.
So the following (returning to original answer) only applies to "older" browsers.
感谢David Richmond的评论:)
Thanks David Richmond from comments :)
因此您会得到 403(禁止访问),因为您的API可能依赖于Cookie进行身份验证/授权(即使在您发送csrfmiddlewaretoken
的情况下,服务器端框架仍可能会希望使用其中的cookie -猜测是Django?).
So you get 403 (Forbidden) because your API likely relies on cookies for authentication/authorization (even in your case, where you send a csrfmiddlewaretoken
, the server-side framework might still expect a cookie with that -- guessing Django?).
要解决此问题,请将credentials: "same-origin"
添加到您的Request
(*),就像这样:
To fix this, add credentials: "same-origin"
to your Request
(*), like so:
let request = new Request(url, {
method: 'post',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
(*)credentials
的有效选项是:
-
omit
:从不发送cookie.这是默认设置(也是您的问题). -
same-origin
:仅当URL与调用脚本的起源相同时才发送cookie. -
include
:始终发送cookie,即使是跨域呼叫也是如此.
omit
: Never send cookies. This is the default (and your problem).same-origin
: Only send cookies if the URL is on the same origin as the calling script.include
: Always send cookies, even for cross-origin calls.
这篇关于将jquery ajax POST请求更改为fetch api POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!