Django在Fetch的POST请求中返回403错误 [英] Django returns 403 error on POST request with Fetch

查看:662
本文介绍了Django在Fetch的POST请求中返回403错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 graphene-django 实现的graphql服务器.我可以像这样使用jquery对其进行查询:

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);
  })

但是,当我尝试使用Fetch进行此调用时,由于CORS问题,我得到了403.我通过在调用之前添加ajaxSetup ...解决了jQuery中的相同问题.

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.

这是使用访存的电话:

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添加到主体,但是没有运气.我尝试添加凭据:包括"为文档说,再次没有运气.我尝试使用凭据:"same-origin",并以不同的方式组合此选项,再次获得相同的结果.网络对此非常安静,我在做什么错了?

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?

推荐答案

解决方案在getCookie()方法中.

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)
      })

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

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;
}

这篇关于Django在Fetch的POST请求中返回403错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆