【问题标题】:angularjs 6 python django rest framework crossdomain api call issueangularjs 6 python django rest框架跨域api调用问题
【发布时间】:2018-12-08 15:38:01
【问题描述】:

我已经用 python 3 配置了 django rest 框架。API 在 postman 中运行良好。但是当我通过我的 angualar 6 项目调用这个 api 时,我面临一个跨域问题。

操作系统:Mac 操作系统

我已包含 oauth2 进行身份验证。它适用于邮递员

API 网址: http://127.0.0.1:7777/api/v1/token/

Angular 6 网站网址: http://localhost:5000/#/login

当我用 angualrjs 调用它时,它显示以下错误。

Mozilla:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:7777/api/v1/token/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Safari:

Failed to load resource: Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load http://127.0.0.1:7777/api/v1/token/. Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin.

铬:

 Failed to load http://127.0.0.1:7777/api/v1/token/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.

python settings.py cors相关部分:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.flatpages',
    'widget_tweaks',
    'rest_framework',
    'oauth2_provider',
    'corsheaders',
] + get_core_apps() 
SITE_ID = 1


ALLOWED_HOSTS = ['127.0.0.1']
CORS_ORIGIN_WHITELIST = ('localhost:5000')
CORS_ORIGIN_ALLOW_ALL = True



MIDDLEWARE_CLASSES = [

    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

我还安装了 oscarcommerce、oauth2、django rest 框架。我在我的系统中使用 angularjs6 和 python 2.7 配置了其他三个网站。一切正常。此问题仅出现在此 python 3 项目中。

【问题讨论】:

标签: angularjs django python-3.x django-rest-framework cross-browser


【解决方案1】:

在您的 settings.py 中添加以下代码

# Corsheaders settings
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = ('*')

它会起作用的......

【讨论】:

    【解决方案2】:

    试试这个:

    ALLOWED_HOSTS = []
    
    CORS_ORIGIN_WHITELIST = (    
    '127.0.0.1:7777',
    'localhost:5000')
    
    CORS_ORIGIN_ALLOW_ALL = True
    

    另请参阅此link 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2016-10-23
      • 2015-02-15
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      相关资源
      最近更新 更多