请求的资源上不存在“Access-Control-Allow-Origin”标头。或 对预检请求的响应未通过访问控制检查

Posted

技术标签:

【中文标题】请求的资源上不存在“Access-Control-Allow-Origin”标头。或 对预检请求的响应未通过访问控制检查【英文标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. OR Response to preflight request doesn't pass access control check 【发布时间】:2017-04-09 09:59:03 【问题描述】:

我收到模板错误

XMLHttpRequest cannot load http://127.0.0.1:8000/api/items/yeasts. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'null' is therefore not allowed access.

打击

api/items/views.py:

import json

from django.shortcuts import render

from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response

@api_view(['GET'])
def serve_yeasts(request):
    """
    Serve up some yeasts
    """
    data = [
        'category': 'Danstar', 'yeasts': ['Danstar 1', 'Danstar 2'],
        'category': 'Fermentis', 'yeasts': ['West Coast', 'American Saison', 'White Wine'],
        'category': 'White Labs', 'yeasts': ['White 1', 'White Saison'],
    ]

    return Response(data=data, status=status.HTTP_200_OK)

        self.get_yeasts = function()

            var data = $.ajax(
              dataType: "json",
              url: "http:/127.0.0.1:8000/api/items/yeasts",
              success: onSuccess,
              error: onError,
            );
         

如果我把它改成

self.get_yeasts = function()

            var data = $.ajax(
              dataType: "json",
              url: "http:/127.0.0.1:8000/api/items/yeasts",
              success: onSuccess,
              error: onError,
              beforeSend: function (request) 
                  request.setRequestHeader("Authorization", "Negotiate");
              ,
              aysnc: true,
            );
         

按照建议,我得到了

XMLHttpRequest cannot load http://127.0.0.1:8000/api/items/yeasts. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

相反。

settings.py:

"""
Django settings for homebrew_app project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'hhp^-#(lx(h4=e3@zq%on7enee0ilngy=p7jybzm#a&kfuau@i'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 3rd party
    'django_extensions',
    'rest_framework',
    'corsheaders',

    # custom
    'calculations',
    'objects',

)

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',
)

ROOT_URLCONF = 'homebrew_app.urls'

WSGI_APPLICATION = 'homebrew_app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    


# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'

CORS_ORIGIN_WHITELIST = (
    'localhost:8000',
    '127.0.0.1:8000',
    'localhost:5000',
    '127.0.0.1:5000',
)

Django CORS 显示正确 https://github.com/ottoyiu/django-cors-headers

http://127.0.0.1:8000/api/items/yeasts/ 确实在浏览器中工作,将酵母列表作为列表返回,并在谷歌浏览器中以 rest_framework 样式呈现。

【问题讨论】:

在 ajax 调用中尝试使用 method:'GET' 【参考方案1】:

当您尝试从另一个域(甚至端口)获取数据时会发生这种情况。解决方案是添加带有调用服务域名值的 http 标头“Access-Control-Allow-Origin”(例如:http://127.0.0.1:8080/ 相应更改端口号)或带有值“*”的“Access-Control-Allow-Origin” ' '127.0.0.1:8000' 上的设置。

【讨论】:

那我该怎么做呢?我正在使用 django 并且已经尝试过 django-CORS-headers 您的意思是将该标头添加到 ajax 或响应中 不,您需要将其添加到您的服务器(nginx 或其他)标头中 你会怎么做? enable-cors.org/server_nginx.html 你可以参考这个 nginx 文档【参考方案2】:

这可能是您需要的 corsheaders 安全设置。尝试将其添加到您的设置中:

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = default_headers + (
    'Access-Control-Allow-Origin',
)

【讨论】:

以上是关于请求的资源上不存在“Access-Control-Allow-Origin”标头。或 对预检请求的响应未通过访问控制检查的主要内容,如果未能解决你的问题,请参考以下文章

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

如何解决请求的资源上不存在“Access-Control-Allow-Origin”标头

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

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

Angular 2请求的资源上不存在“Access-Control-Allow-Origin”标头[重复]

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