【发布时间】: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