Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

jquery - Django returns 403 error on POST request with Fetch

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The solution was in the getCookie() method.

  fetch("/graphql", {
        method: "POST",
        credentials: "same-origin",
        headers: {
          "X-CSRFToken": getCookie("csrftoken"),
          "Accept": "application/json",
          'Content-Type': 'application/json'
        },
        body:JSON.stringify(query)
      })

And of course the method has to be on the same page. Taken from Django Docs.

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...