jquery – Django-cors-headers无效

我的
django版本是1.8.6.我将corsheaders文件夹复制到项目文件夹中.我已经安装了django-cors-headers(版本1.1.0).这是我的setting.py:

    INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'MyWebsite_app',
    'storages',
    'rest_framework',
    'corsheaders',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

CORS_ORIGIN_ALLOW_ALL = True

这是我的jquery:

function getLeague() {
$.ajax({
    url: 'http://otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        alert('Success');
    },
    error: function(data) {
        alert('Fail');
    }
    });
}

它在执行getLeague()时保持警告“失败”.当我看到控制台时,它显示“XMLHttpRequest无法加载http://otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx.请求的源上没有Access-Control-Allow-Origin标头”.我应该在urls.py或view.py中添加一些代码吗?谢谢.

最佳答案 最好在您的应用程序中创建一个代理,然后再调用另一个域并返回数据:

function getLeague() {
  $.ajax({
    url: '/crossdomainData',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        alert('Success');
    },
    error: function(data) {
        alert('Fail');
    }
    });
}

当你使用django时,你可以导入这个Django HTTP Proxy.

Introduction

Django HTTP Proxy provides simple HTTP proxy functionality for the Django web development framework. It allows you make requests to an external server by requesting them from the main server running your Django application. In addition, it allows you to record the responses to those requests and play them back at any time.

另一种选择是taken from this post在0700回答.

import urllib2
    def crossdomainData(request):
        url = "http://otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx"
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        return HttpResponse(response.read(), content_type="application/json")
点赞