我已经用python 3配置了django rest框架。API在邮递员中运行良好。但是,当我通过angualar 6项目调用此api时,面临一个跨域问题。
操作系统:Mac OS
我已包含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).
苹果浏览器:
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项目上出现此问题。
在您的settings.py中添加以下代码
# Corsheaders settings
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = ('*')
它会工作....
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。