0
votes

I've built a REST API and I'm following along with this tutorial: https://www.youtube.com/watch?v=hISSGMafzvU&t=14s

I've completed all up until 13minutes. addition of a JS script into the html template. When I run and check the console I get: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

I have no idea what part of my projects the CORS header goes into?

<script type="text/javascript">

        buildList()
        function buildList(){
            var wrapper = document.getElementById('list-wrapper')

            var url = 'http://127.0.0.1:8000/api/task-list/'

            fetch(url)
            .then((resp) => resp.json())
            .then(function(data){
                console.log('Data:', data)
            })
        }
</script>
1

1 Answers

0
votes

You must add pip install django-cors-headers to your Django app and configure it to allow requests. And then add it to your installed apps:

#settings.py

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

You will also need to add a middleware class to listen in on responses:

#settings.py
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

Just allow all origins to make cross-site HTTP requests:

#/settings.py
CORS_ORIGIN_ALLOW_ALL = True

Note: If you are in development, you can allow all CORS of any origin. But don't do that in production.

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    'https//:yourdomain',
)

I hope it helps!