2

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

6
  • Check ALLOWED_HOSTS in settings.py. Set it as this ALLOWED_HOSTS = ["*"] Commented May 10, 2019 at 7:07
  • also added ALLOWED_HOSTS = ['*'] in settings.py Commented May 10, 2019 at 7:14
  • Remove Access-Control-Allow-Origin": "*" from your axios call in your frontend JavaScript code. Commented May 10, 2019 at 9:17
  • Can't you add access control to your response from django view? response = HttpResponse(json.dumps(string)) response["Access-Control-Allow-Origin"] = "*" return response Commented May 10, 2019 at 10:31
  • still same error occurs Commented May 11, 2019 at 16:19

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.