[django, React] Has been blocked by CORS policy? net::ERR_FAILED?

forhjy
2 min readJan 1, 2021

--

Here’s a solution.

If you don’t allow cross domain at server side, it will raise an CORS error when you try to access to API. Even though both django and React run on localhost, they considered as different server because they run on different ports (8000, 3000 respectively).

[Solution for CORS error]

At Server Side

pip3 install django-cors-headers

For local development

Add below to your project section settings.py. This allows all the requests.

CORS_ORIGIN_ALLOW_ALL = TrueCORS_ALLOW_CREDENTIALS = True

For distribution

You cannot allow all the requests when you distribute your service. For more information about options, find this github.

CORS_ORIGIN_ALLOW_ALL = FalseCORS_ORIGIN_WHITELIST = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000"
]

[Solution for net::ERR_FAILED]

At Front Side

Make sure to put / in the end. If you done nothing with APPEND_SLASH option, django automatically append slash to url. If you try to reach api without slash at the end, it would not be able to get data from api.

axios.get('http://localhost:8000/api/User/');

Refresh the page and check development tool!

--

--

forhjy
forhjy

Written by forhjy

Software Engineer Based in Seoul

Responses (1)