I have a web application with react frontend and django backend.
Some of the APIs from the backend are being blocked by cors policy whereas others are not. For example, The API to fetch blog posts
const res = await axios.get(`${process.env.REACT_APP_API_URL}/blog/posts`) is returning data but the API for individual posts const res = await axios.get(`${process.env.REACT_APP_API_URL}/blog/${slug}`); is blocked. The register and login APIs are blocked too. I have added the domain to the list of allowed url in settings.py but that didn't solve the issue.
The error I'm getting in the detail page is:
undefined:1 Access to XMLHttpRequest at 'https://.api.example.co/blog/undefined' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
settings.py
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
'http://127.0.0.1:8000',
'http://localhost:3000',
'https://example.co',
]
CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:8000',
'http://localhost:3000',
'https://example.co',
]
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
CORS_REPLACE_HTTPS_REFFERER = True
When I use Postman to test the API's everything works properly. But In react app it's only the API that list posts or items that are returning data, others are blocked. Why such behaviour, and how do I fix it?
This problem have two parts. 1.what is the problem? 2.How can you solve this problem completely or presently? I think your problem is from your backend api that not add your host to allow Host in their code. When you run your project a virtual host created on your system that call your Api from your virtual server, that is just the reason that your request had failed from your run project and pass from postman. Actually change your backend code or web server settings that can allow from another origins can solve your problem. But if you dont access your backend team and you want to solve your problem with yourself you can add your browser cores header extension that can pass your request for your test case. At the end i give you good extension for your chrome browser. https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en