请求的资源上不存在“Access-Control-Allow-Origin”标头。

时间:2018-02-04 17:48:47

标签: python ajax django api header

我使用ajax来调用以下网址:

https://www.bittrex.com/api/v1.1/public/getticker?market=usdt-btc

我收到以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 

我已经安装了django-cors-headers,我的settings.py看起来像这样:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'crispy_forms',
    # The following apps are required:
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
)


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
CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8000',
)

为什么我仍然收到错误?

**我已经阅读了与此相关的所有其他答案,但他们没有帮助我。我也使用了chrome插件,它确实可以使用它,但我想要一个没有它的解决方案**

Django Version = 1.8

2 个答案:

答案 0 :(得分:0)

根据文档,配置看起来很好。我只是把它与我的配置进行了比较,它几乎是一样的。由于我只在一个网站上使用我的API,我在 CORS_ORIGIN_WHITELIST 中配置了它,您也可以尝试这个以查看它是否响应。

此外,尝试删除所有python缓存文件并重新启动应用程序服务器,可能是未加载的设置。

答案 1 :(得分:0)

这不是您的应用程序问题,即django问题,因为CORS是一个http标头,让用户代理获得与您的资源不同的资源的权限。这是一个浏览器问题,因此在django中添加CORS应用程序将无效。 更多信息在这里 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

尝试在ajax请求中添加 crossDomain:true