美文网首页
Django跨域

Django跨域

作者: 叶扬风起 | 来源:发表于2019-09-19 17:32 被阅读0次

1. 安装django-cors-headers模块

pip3 install django-cors-headers

2. 注册AAP

在setting里面修改

INSTALLED_APPS = [
    ...
    'corsheaders'
]

3. 添加中间件

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

4. 跨域设置

#跨域
# 跨域允许的请求方式,可以使用默认值,默认的请求方式为:
# from corsheaders.defaults import default_methods
CORS_ALLOW_METHODS = (
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
)

# 允许跨域的请求头,可以使用默认值,默认的请求头为:
# from corsheaders.defaults import default_headers
# CORS_ALLOW_HEADERS = default_headers

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

# 跨域请求时,是否运行携带cookie,默认为False
CORS_ALLOW_CREDENTIALS = True
# 允许所有主机执行跨站点请求,默认为False
# 如果没设置该参数,则必须设置白名单,运行部分白名单的主机才能执行跨站点请求
CORS_ORIGIN_ALLOW_ALL = True
#允许访问的来源,但是需要把CORS_ORIGIN_ALLOW_ALL设为False
CORS_ALLOW_HEADERS = ('*')
#部署服务器时使用
ALLOWED_HOSTS = ['*']


#如果要单独设置某些端口访问
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
    'http://localhost:8080',
    'http://localhost',

    'http://127.0.0.1:8080',
    'http://127.0.0.1',

    'http://127.0.0.1:8000',
    'http://127.0.0.1',

    'http://192.168.2.140:8080',
    'http://192.168.2.140',
]

相关文章

网友评论

      本文标题:Django跨域

      本文链接:https://www.haomeiwen.com/subject/ycvructx.html