Django 在使用 Fetch 的 POST 请求上返回 403 错误

Ska*_*Ska 2 django ajax jquery csrf fetch

我有一个使用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);
  })
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用 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();
    })
Run Code Online (Sandbox Code Playgroud)

我尝试以与我在 jQuery 示例中所做的类似的方式将 csrfmiddlewaretoken 添加到正文中,但没有运气。我尝试添加凭据:'include' 正如文档所说,再次没有运气。我尝试使用凭据:'same-origin' 并以不同的方式组合此选项,再次得到相同的结果。Web 对此异常安静,我做错了什么?

Ska*_*Ska 9

解决方案是在 getCookie() 方法中。

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

当然,该方法必须在同一页面上。取自Django 文档。

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;
}
Run Code Online (Sandbox Code Playgroud)