【发布时间】:2017-11-09 18:44:07
【问题描述】:
我有一些我已经使用 $.ajax 发布到 API 的 json 数据,但我想更新它以使用 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())
我尝试过使用各种不同的标头、内容编码并将数据作为表单数据发送:
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
});
...
任何帮助都会很棒,如果您需要更多信息,请告诉我
谢谢
【问题讨论】:
-
为什么不标头:
headers: { 'Content-Type': 'application/json' }? -
我试过了,但似乎没有用。我会再试一次,也许是其他事情搞砸了!
-
@sideshowbarker — 工作 (jQuery) 代码使用 www 表单编码。没有任何迹象表明服务器支持 JSON 格式的请求。
标签: javascript ajax fetch-api