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.
No 'Access-Control-Allow-Origin' header is present on the requested resource React Django error
1.1k views Asked by Anurag Tiwari At
2
There are 2 answers
1
On
This error is being caused by your django backend. Here is what you can do to fix it:
- Install django-cors-headers using pip like @seddouguim suggested
- Add 'corsheaders' to your installed apps in your django settings.py file
- 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 setCORS_ORIGIN_ALLOW_ALL = True
(good for dev but not for production environments) - 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
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/