Home > Enterprise >  Django Rest CORS with Vue JS
Django Rest CORS with Vue JS

Time:08-03

I have a django rest framework api running on http://127.0.0.1:8000/ and a Vue JS app running on http://127.0.0.1:5173/. When I make a request from the vue app I get the origin has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response. I have installed django cores and below are the setting in my settings.py

Installed Apps

"corsheaders",

Middleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

And allowed

CORS_ORIGIN_ALLOW_ALL = True

Vue JS Code

axios.defaults.baseURL = 'http://127.0.0.1:8000/'; # In axios.js

async login() {
    const response = await axios.get('users', {
                username: this.username,
                password: this.password
            });
    console.log(response)
},

CodePudding user response:

In doc write

CORS_ALLOW_ALL_ORIGINS: bool

If True, all origins will be allowed. Other settings restricting allowed origins will be ignored. Defaults to False.

Setting this to True can be dangerous, as it allows any website to make cross-origin requests to yours. Generally you'll want to restrict the list of allowed origins with CORS_ALLOWED_ORIGINS or CORS_ALLOWED_ORIGIN_REGEXES.

Previously this setting was called CORS_ORIGIN_ALLOW_ALL, which still works as an alias, with the new name taking precedence

https://github.com/adamchainz/django-cors-headers#cors_allow_all_origins-bool

CodePudding user response:

So after hours of stressing and frustrations, this is how I solved this. I maintained my Vue JS code as below

async login() {
            const response = await axios.post('auth/login/', {
                        username: this.username,
                        password: this.password
                    });
            console.log(response)

        },

and in my Django settings.py file I had to add these two lines:

CORS_ALLOW_HEADERS = "*"
CORS_ORIGIN_WHITELIST = [
    'http://127.0.0.1:5173',
]

Since Alex pointed out that CORS_ALLOW_ALL_ORIGINS = True can be dangerous hence the CORS_ORIGIN_WHITELIST block.

  • Related