-1

I'm trying to POST from a website with different origin. I use JavaScript to call the API.

A minimal example of what I've done is shown:

JavaScript:

options = {method: 'POST',
      // mode: 'no-cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: formData
    }
    fetch(url, options).then(response => {
      console.log(response)
    }).catch(err => {
      console.error(err)
    });
  }

Django Rest Framework based class:

class ImageUpload(APIView):

    def post(self, request, format=None):
        print("data:", request.data)
        print("file:", request.FILES)

        response = Response(status=status.HTTP_201_CREATED)
        response['Access-Control-Allow-Origin'] = "*"
        response["Access-Control-Allow-Headers"] = "*"
        print(response)
        return response

    def options(self, request, *args, **kwargs):
        response = Response()
        response['Access-Control-Allow-Origin'] = "*"
        response["Access-Control-Allow-Headers"] = "*"
        print(response)
        return response

With this example, I get CORS error that Cross-Origin Request is Blocked. This is due to the missing header. Interestingly, upon calling the API, my django console doesn't print a single line which it was supposed to upon calling the POST request. How did DRF send a response without going into def post? Before calling POST, OPTIONS is called which behaves perfectly as it should have. I even got the response printed on console.

Also, another observation is, the API works perfectly fine when i uncomment mode: 'no-cors'.

Upon researching, I found that I can use django-cors-headers, but opening up CORS to all the views of the entire project seems to be an overkill. As per the documentation of DRF and as suggested by this answer, I should have been correctly using the headers, but that would be the case, if I would atleast enter the post function defined in the class.

Can someone point out what is going on here and where did I go wrong?

1 Answers1

0

For anyone who lands up to this question, found that headers: {'Content-Type': 'application/json'}, is causing the errors. I'm not sure why, but removing this solved the issue. If someone can try to explain this, would be a lot helpful :)