djangogetcorsxmlhttprequestfetch

Django Rest Framework - Cross Origin Resquest got blocked


I'm developing an API using Django Rest Framework. I'm trying to list or create an "Article" object, but when i'm trying to access the console gives me this error:

I host my frontend at http://localhost:3000 and sending request to 127.0.0.1:8000


Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
http://127.0.0.1:8000/api/articles/. 
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing). 
Status code: 200.

With this in setting.py, I got the above error

CORS_ALLOWED_ORIGINs = [
    "http://localhost:3000",
]

but if using this code then it runs smoothly

CORS_ORIGIN_ALLOW_ALL = True 

This is my GET request

useEffect(() => {
    fetch("http://127.0.0.1:8000/api/articles/", {
        'method': "GET",
        headers: { 
            'Content-Type': 'application/json',
            'Authorization': 'Token 746a97c3f72a5fc388762c5732e2c8340fc75ba9',
        }
    })
    .then(res => res.json())
    .then((data) => setArticles(data))
    .catch((error) => console.log(error))
  }, []);

Other configurations in setting.py seem to be set up correctly.


Solution

  • You have a typo in CORS_ALLOWED_ORIGINs setting (lowercase s), try

    CORS_ALLOWED_ORIGINS = [
        "http://localhost:3000",
    ]
    

    And make sure your application is running on http://localhost:3000 as http://127.0.0.1:3000 could be handled differently.