1

I have a Django local sever that refer to 8000 port number, And a local nginx that load 2080 port number html page.

I install django-cross-header package for resolving cross-domain error.

django-cross-header config in settings.py:

CORS_ALLOW_CREDENTIALS = True


CORS_ORIGIN_ALLOW_ALL = True

  CORS_ALLOW_HEADERS = (
         'x-requested-with',
         'content-type',
         'accept',
         'origin',
         'authorization',
         'x-csrftoken'
 )

  CORS_ORIGIN_WHITELIST = (
          '127.0.0.1:2080',
          'localhost:2080'
  )

Config angularjs is like this:

portman.config(function ($routeProvider, $interpolateProvider, $httpProvider) {
     $routeProvider.otherwise('/');
     $httpProvider.defaults.headers.common['X-CSRFToken'] = csrftoken;
     $interpolateProvider.startSymbol('{$').endSymbol('$}');
     delete $httpProvider.defaults.headers.common['X-Requested-With'];

 });
 portman.constant('ip','http://127.0.0.1:8000/');

Get method code in angularjs is:

$http({
         method: 'GET',
         url: ip+'api/v1/dslam/events',
     }).then(function (result) {
        $scope.dslam_events = result.data;
     }, function (err) {

    });

request header is : Provisional headers are shown

Accept:application/json, text/plain, */*
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36
X-CSRFToken:ztouFO8vldho97bWzY9mHQioFk3j6h5V

After loading the page I see this error:

XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/dslam/events.The request was redirected to 'http://127.0.0.1:8000/api/v1/dslam/events/', which is disallowed for cross-origin requests that require preflight.

But when i send request from console it will corectly response from django server, my jquery code :

$.ajax({
            type: 'GET',
            url: "http://5.202.129.160:8020/api/v1/dslam/events/",
            success:function(data){
             console.log(data);
            }
        });

request header is:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,fa;q=0.6,pt;q=0.4
Connection:keep-alive
Host:127.0.0.1:8000
Origin:http://127.0.0.1:2080
Referer:http://127.0.0.1:2080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36

please help me.

Saeed Ghareh Daghi
  • 1,164
  • 1
  • 13
  • 21

3 Answers3

1

You need to add corsheaders to your installed apps.

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

Add corsmiddleware to the middleware classes.

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

And finally you are missing one slash at the end of the url "/". Also you should add the csrf token at your http request so that it works with unsafe http methods like POST, PATCH, PUT AND DELETE.

$http({
    method: 'GET',
    url: ip+'api/v1/dslam/events/',
    'X-CSRFToken' : $cookies.get('csrftoken')
}).then(function (result) {
    $scope.dslam_events = result.data;
}, function (err) {

});

In order to the $cookies service to work, you need to install the ngCookies angular module and that's it.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
0

Try this for enabling cross origin

https://github.com/ottoyiu/django-cors-headers
Ashish Gupta
  • 1,153
  • 12
  • 14
-1

I had the same problem as you. I just needed to add the following settings in httpd.conf and the angular app. That's it, just go through the following steps.

<IfModule mod_headers.c>
SetEnvIf Origin (.*) AccessControlAllowOrigin=$1
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
</IfModule> 

And in the angular app

angular.module('app', ['ngCookies'])
    .config([
   '$httpProvider',
   '$interpolateProvider',
   function($httpProvider, $interpolateProvider, $scope, $http) {
       $httpProvider.defaults.withCredentials = true;
       $httpProvider.defaults.xsrfCookieName = 'csrftoken';
       $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
   }]).
   run([
   '$http',
   '$cookies',
   function($http, $cookies) {
       $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
   }]);

Here are the details about CORS.

Community
  • 1
  • 1
Akshay Kumbhar
  • 279
  • 3
  • 6