Django returns 403 error on POST request with Fetch

后端 未结 2 374
忘了有多久
忘了有多久 2020-12-11 13:14

I have a graphql server implemented using graphene-django. I can make queries to it using jquery like this:

function allIngredients() {
    return \'query{al         


        
相关标签:
2条回答
  • 2020-12-11 13:47

    If you want to make that post request form a different domain (in case when the front of the application is in React or angular and the backend is in Django), make sure the add following in the settings file:

    1. Update the INSTALLED_APPS to use 'coreHeaders' :

      INSTALLED_APPS = [
      'corsheaders',
      ]

    2. White list your front end domain by adding following to settings file again:

      CORS_ORIGIN_WHITELIST = ( 'localhost:8080', )

    Now allow the permission to make this post request for anyone:

    Note: Should be used in the cases where you don't need to authenticate the users for posting anything on our server, say, when a new user registers for the first time.

    from rest_framework.permissions import AllowAny
    
    class CreateUser(APIView):
        permission_classes = (AllowAny,)
        def post(self, request, format=None):
            return(Response("hi"))
    
    0 讨论(0)
  • 2020-12-11 13:58

    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;
    }
    
    0 讨论(0)
提交回复
热议问题