Thusitha Deepal
Thusitha Deepal

Reputation: 1546

Cors error when accessing Django Rest API from front end Using Axios

Accessing django Rest API using axios gives following error

Access to XMLHttpRequest at 'http://api.localhost:8080/auth/register-shop/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

I added django cors headers as mention in this link https://pypi.org/project/django-cors-headers/

frontend page

 axios({
                                method: 'post',
                                url: 'http://api.localhost:8080/auth/register-shop/',
                                //url: 'http://api.yuniq.ml/auth/register-shop/',

                                headers: {
                                        "Access-Control-Allow-Origin": "*",
                                        "content-type": "application/json"
                                },
                                data: {

                                        "name": Name,
                                        "address": Address,
                                        "city": City,
                                        "postalC ode": PostalCode,
                                        "telephone": Telephone,
                                        "openTime": Opentime,
                                        "closeTime": Closetime,
                                        "image_url": Image_url  //still not working 

                                }
                        }).then(function (response) {
                                console.log(response);
                        })
                                .catch(function (error) {
                                        console.log(error);
                                });


                }

settings.py

INSTALLED_APPS = ['corsheaders']


MIDDLEWARE = [

    'django_hosts.middleware.HostsRequestMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware' , #add cors middleware
    'django.middleware.common.CommonMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django_hosts.middleware.HostsResponseMiddleware',
]



CORS_ORIGIN_ALLOW_ALL = True

error not solved after doing this

Upvotes: 2

Views: 3677

Answers (3)

user12538579
user12538579

Reputation: 19

Your axios request should not include this header: "Access-Control-Allow-Origin": "*",

That should only be included in the server's response. Try removing it from your axios request.

Upvotes: 1

shahab kamali
shahab kamali

Reputation: 341

I had the same problem and did the below steps:

  • I checked what headers are sending from the Axios.
  • make sure this package is installed

'pip install django-cors-headers'

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

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

Now there are two options:

1 - Allow access to all domains by just Adding the following variables in settings.py:

ALLOWED_HOSTS=['*']

CORS_ORIGIN_ALLOW_ALL = True

2 - Do not allow access to all the domains, but the one which you are consuming the API. Add the following variables in settings.py

ALLOWED_HOSTS=['http://localhost:5000']

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = ( 'http://localhost:5000', )

Also you can define allow hearders in setting.py if you want to send a specific header with your request.

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_HEADERS = [   
    ...
    'Currency',
    ...
 ]

checking out this can help you:

https://dzone.com/articles/how-to-fix-django-cors-error

Upvotes: 3

Md. Tanvir Raihan
Md. Tanvir Raihan

Reputation: 4285

I recently faced same issue and i have solved it. I am also using corsheaders to avoid CORS errors and it works fine till i introduce Authentication. The same problem starts again for those api's which permission is set to IsAuthenticated. So i add the certain host in my ALLOWED_HOSTS list in settings.py and its worked. There are two options to add hosts.

Option 1. ALLOWED_HOSTS=["*"]

Option 2. ALLOWED_HOSTS=['your host1', 'your host2', 'your host3', ......].

NOTE: I don't prefer Option 1, because it will raise security issues. So choose Option 2.

Upvotes: 0

Related Questions