I have a graphql server implemented using graphene-django. I can make queries to it using jquery like this:
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);
})
However, when I try this call with Fetch, I get a 403, because of the CORS issue. I solved the same problem in jQuery by adding ajaxSetup... before the call.
Here's the call using 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();
})
I tried adding csrfmiddlewaretoken to the body in the similar way as I did in jQuery example, no luck. I tried adding credentials: 'include' as the docs say, again no luck. I tried with credentials: 'same-origin' and combining this options differently, again the same result. Web is unusually quiet about this, what am I doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…