7

Django 通过设置 CORS 解决跨域问题

 3 years ago
source link: https://www.wenyuanblog.com/blogs/django-cors-settings.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Django 通过设置 CORS 解决跨域问题

一、Ajax 跨域请求

Ajax 请求一个目标地址为非本域(协议、主机、端口任意一个不同)的 web 资源。

  • 前端
    • http://192.168.10.50:8080
  • 后端
    • http://192.168.10.50:8000

Ajax 跨域请求保护的作用:防止跨站的攻击。

二、如何解决跨域的访问

当我们在现实当中有需要跨域访问资源,有两种解决方案:

  • 前端解决:jsonp
  • 后端解决(Django):CORS 专门解决方案

这篇文章主要介绍使用 Django 框架进行开发时的后端解决方案。

三、Django 解决跨域问题

Django 框架中通过 django-cors-headers 这个模块解决。

pip install django-cors-headers

2. 注册应用

注册到 settings 的 INSTALLED_APPS 中。

python
INSTALLED_APPS = ( ... 'corsheaders', ... )

3. 添加到中间件

添加到 settings 的 MIDDLEWARE 中,一般放在 django.middleware.csrf.CsrfViewMiddleware 前面。

python
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ]

4. 添加白名单

添加允许访问的白名单,凡是出现在白名单的域名都可以访问后端接口。

python
# 添加 CORS 配置 # 1. 设置白名单 CORS_ORIGIN_WHITELIST = ( '127.0.0.1:8080', 'localhost:8080', 'http://192.168.10.50:8080', # 凡是出现在白名单中的域名,都可以访问后端接口 ) # 2. 设置 CORS Cookie CORS_ALLOW_CREDENTIALS = True # 指明在跨域访问中,后端是否支持对cookie的操作

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK