【发布时间】:2017-10-07 17:37:33
【问题描述】:
我有一个使用graphene-django 实现的graphql 服务器。我可以像这样使用 jquery 对其进行查询:
function allIngredients() {
return 'query{allProducts{edges{node{name}}}}'
}
var query = allIngredients();
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
$.post("/graphql", {query: query}, function(response) {
console.log(response);
})
但是,当我尝试使用 Fetch 进行此调用时,由于 CORS 问题,我得到了 403。我通过在调用之前添加 ajaxSetup... 解决了 jQuery 中的相同问题。
这是使用 fetch 的调用:
fetch('/graphql', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
csrfmiddlewaretoken: '{{ csrf_token }}',
query:`{allProducts{
edges{
node{
id
name
orderPrice
sellPrice
}
}
}`})
}
)
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
我尝试以与在 jQuery 示例中类似的方式将 csrfmiddlewaretoken 添加到正文中,但没有运气。我尝试添加凭据:'include' as the docs say,再次没有运气。我尝试使用 credentials: 'same-origin' 并以不同的方式组合此选项,再次获得相同的结果。网络对此异常安静,我做错了什么?
【问题讨论】:
标签: jquery ajax django fetch csrf