开发者社区> 问答> 正文

angularjs 6 python django rest框架跨域api调用问题

我已经用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项目上出现此问题。

展开
收起
祖安文状元 2020-02-22 18:12:39 967 0
1 条回答
写回答
取消 提交回答
  • 在您的settings.py中添加以下代码

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

    它会工作....

    2020-02-22 18:13:26
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Boot2.0实战Redis分布式缓存 立即下载
CUDA MATH API 立即下载
API PLAYBOOK 立即下载