django-cors-headers doesn't let a GET-request bypass the CORS blockage

59 Views Asked by At

I have an app with Django backend (localhost:8000) and Vue.js frontend (localhost:5173). I'm trying to fetch data from the backend to the frontend via GET-request with Axios. Here's the App.vue contents:

<template>
   <div class="app">
     <button v-on:click="fetchData">Get Data</button>
     <data-list v-bind:items="items"/>
   </div>
</template>

<script>
import DataList from "@/components/DataList.vue";
import axios from "axios";

export default {
 components: {
   DataList
 },
 data() { 
   return {
     items: [],
   }
 },
 methods: { 
   async fetchData () {
     try {
       const response = await axios.get('http://127.0.0.1:8000')
       console.log(response.data.result)
       this.items = response.data.result
     } catch (e) {
       alert(e.toString())
     }
   }
 },
 mounted() {
   this.fetchData()
 }
}
</script>

However, all requests are being blocked by the CORS policy with an error: Access to XMLHttpRequest at 'http://127.0.0.1:8000' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

django-cors-headers module is installed and registered in settings.py:

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

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ...
]

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    'http://localhost:8000',
    'http://localhost:5173',
)

I've made sure that 'corsheaders.middleware.CorsMiddleware' is the first on the MIDDLEWARE list as many answers to the similar questions suggest.

I've also tried setting CORS_ORIGIN_ALLOW_ALL = True, but it made no difference.

How do I configure the application settings so that the requests are allowed to go through?

Thanks.

0

There are 0 best solutions below