No 'Access-Control-Allow-Origin' header is present on the requested resource React Django error

1.1k views Asked by At

Access to fetch at 'http://localhost:8000/api/product/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

2

There are 2 answers

0
seddouguim On

I don't have any experience with Django but I know that the error is because you have to enable CORS which will allow you to make api calls to domains other than the source of your call (or on a different port). Check for the documentation to see how to enable CORS.

https://pypi.org/project/django-cors-headers/

1
Daniel Miranda On

This error is being caused by your django backend. Here is what you can do to fix it:

  1. Install django-cors-headers using pip like @seddouguim suggested
  2. Add 'corsheaders' to your installed apps in your django settings.py file
  3. At the bottom of the same settings.py file, you can either add a setting called CORS_ORIGIN_WHITELIST=['localhost:3000'] (or whatever URL you want to add), OR you can set CORS_ORIGIN_ALLOW_ALL = True (good for dev but not for production environments)
  4. Lastly set CORS_ALLOW_HEADERS = ("x-requested-with", "content-type", "accept", "origin", "authorization", "x-csrftoken")

And you should be good to go

Please feel free to let me know if you encounter any other issues