【问题标题】:CORS with django and angularjs带有 django 和 angularjs 的 CORS
【发布时间】:2016-04-20 13:17:34
【问题描述】:

我目前正在尝试使用 Django 作为后端使用 AngularJS 创建一个 Web 界面,但我得到了常见的 CORS 错误:XMLHttpRequest 无法加载 http://fatboyapi.ddns.net:8000/o/revoke_token/?client_id=xxx&client_secret=xxx&token=xxxxxxxx。请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://fatboy.ddns.net:8000' 因此不允许访问..

当 CORS_ORIGIN_ALLOW_ALL 标志设置为 True 时,一切正常,但显然不安全。我调用的终点是 django-oauth-toolkit 提供的 o/token/

我将这些添加到我的白名单的链接中。 'http://fatboyapi.ddns.net:8000', 'http://fatboy.ddns.net:8000'

当我在 firefox 或 Postman 上使用 restclient 并结合 CORS_ORIGIN_ALLOW_ALL = False 时,我没有收到任何错误

我用来调用我的api的地址是'http://fatboy.ddns.net:8000'

这是我在 Django 中使用的包

boto==2.38.0
contextlib2==0.4.0
Django==1.9
django-braces==1.8.1
django-cors-headers==1.1.0
django-custom-user==0.5
django-debug-toolbar==1.4
django-guardian==1.3.2
django-indexer==0.3.0
django-oauth-toolkit==0.9.0
django-paging==0.2.5
django-storages==1.1.8
django-templatetag-sugar==1.0
djangorestframework==3.3.1
docutils==0.12
eventlet==0.17.4
greenlet==0.4.9
lockfile==0.12.2
oauthlib==1.0.1
Pillow==2.9.0
psycopg2==2.6.1
six==1.10.0
sqlparse==0.1.18
wheel==0.24.0

这是我的 settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'custom_user',
    'guardian',
    'rest_framework',
    'oauth2_provider',
    'scheduleauthentication',
    'punchclock',
    'debug_toolbar',
)

AUTH_USER_MODEL = 'custom_user.EmailUser'

ANONYMOUS_USER_ID = -1

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
)

MIDDLEWARE_CLASSES = (
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    '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',
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
)

ROOT_URLCONF = 'punchclock.urls'

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    'https://fatboyapi.ddns.net',
    'https://fatboy.ddns.net',
    'http://fatboyapi_i.ddns.net',
    'http://fatboy_i.ddns.net',
    'http://fatboyapi.ddns.net:8000',
    'http://fatboy.ddns.net:8000'
)

CORS_ALLOW_CREDENTIALS = False

CORS_ALLOW_METHODS = (
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'OPTIONS'
    )

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'punchclock.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'NAME': 'pc',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'HOST': 'localhost',
        'USER': 'postgres',
        'PASSWORD': 'fatboy',
        'PORT': '5432',
    }

}
#REST-FRAMEWORK
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
    )
}

谢谢!

【问题讨论】:

  • 有什么问题?你说它在“Firefox 和 Postman 结合......”中工作:)
  • 我想将:CORS_ORIGIN_ALLOW_ALL 设置为 FALSE,并让我的应用程序在没有 CORS 错误的情况下运行。因为有了这个设置,它只适用于邮递员,它不在我的应用程序中(我得到了我在问题开头写的错误)。

标签: javascript python angularjs django cors


【解决方案1】:

使用 CORS 标头,您可以限制允许哪些客户端发出请求以及允许哪些方法。

访问控制允许来源:http://siteA.com

访问控制允许方法:GET、POST、PUT

还有其他标题,谷歌一下:)

另外,Angular 是在 Apache 或 Node 上运行吗?如果是这样,那么您可以向同一域发出请求,例如http://yourangulardomain.com/api/request/that/i/want/to/go/to/my/django/server

然后在你的 Apache/Node 配置中添加一个重写规则来重写请求。这样可以规避跨源问题。

使用 npm 模块 connect-modrewrite(主要基于 Apache 重写规则)在 Node(服务于 Angular)上使用的类似重写规则是 ...

middleware: [
      rewrite([
        '^/api/(.*)$ http://10.20.1.20:9100/$1 [P]',
        '^[^\\.]*$ /index.html [L]'
      ])
    ]

这基本上将 URL 中包含 /api 的请求发送到差异服务器,但将其他所有内容路由到 index.html

不知道为什么这不会干扰对 CSS 文件等的请求!!

希望对您有所帮助:)

【讨论】:

  • 您好,感谢您的回复。我对此的理解是,通过向我的 cors_origin_whitelist(例如 fatboy.ddns.net:8000)添加一个元素,Django 会自动将以下标头发送到客户端“Access-control-allow-origin: fatboy.ddns.net:8000” .该标头可以在我的浏览器上显示 http 响应的内容。目前,这是我得到的响应头:Cache-Control → no-store Content-Type → application/json Date → Sat, 16 Jan 2016 05:15:01 GMT Pragma → no-cache Server → WSGIServer/0.2 CPython /3.4.2 X-Frame-Options → SAMEORIGIN(邮递员)
  • 我最近使用代理进行了配置,在其中添加了 Access-control-allow-origin,AngularJS 能够毫不费力地显示结果。现在,我不明白的是,尽管我将域名添加到了白名单中,但为什么 Django 不会向我发送该标头。我需要用 AngularJS 发送一些具体的东西吗?或者我可能需要在 settings.py 文件中配置其他内容。谢谢!
  • 如果请求中发送了相同的标头,那么响应应该是相同的。我将调查 Angular 发送的标题,并将其与成功邮递员请求发送的标题进行比较。使用 curl 测试各种标题。另外,角度是否提出了 OPTIONS 飞行前请求?当您执行跨域 POST 或 PUT 时,即使您没有请求,也会默认发出 OPTIONS 请求。如果 OPTIONS 请求失败,那么您的实际请求(POST 或 PUT)将永远不会发出。查看浏览器的 NET 选项卡,查看 Angular 是否发出 OPTIONS 请求。
  • @NOaMTL 你曾经解决过这个问题吗?我面临着类似的问题-stackoverflow.com/questions/50846958/…
猜你喜欢
  • 2014-01-14
  • 2021-07-31
  • 1970-01-01
  • 2014-12-25
  • 2018-03-25
  • 2016-03-23
  • 2016-04-19
相关资源
最近更新 更多