2016-11-25 94 views
-1

我得到的模板錯誤請求的資源上沒有「Access-Control-Allow-Origin」標頭。或對預檢要求未通過訪問控制檢查

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 /項目/ 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([email protected]%on7enee0ilngy=p7jybzm#a&[email protected]' 

# 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/確實在瀏覽器中工作,返回酵母作爲一個列表的列表,並在谷歌Chrome rest_framework風格渲染。

+0

一旦與方法試試:「GET」在Ajax調用 – neelima

回答

1

,當你正試圖從另一個域(偶數端口)獲得的數據會發生這種情況。解決方案是使用您的主叫服務域名的值(例如:http://127.0.0.1:8080/相應地更改端口號)或使用值'*'設置的'Access-Control-Allow-Origin'來添加http頭部'Access-Control-Allow-Origin'在'127.0.0.1:8000'上。

+0

所以我怎麼做呢?我使用Django和已經嘗試過的Django-CORS-頭 – codyc4321

+0

你的意思是頭添加到 – codyc4321

+0

沒有,你需要把它添加到你的服務器的AJAX或響應(nginx的或其他)報頭 –

相關問題