Django Access-Control-Allow-Origin

具体报错方式:XMLHttpRequest cannot load http://127.0.0.1:8000/api/infos. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://www.xxx.xxx:8000’ is therefore not allowed access

Django-cors-headers 扩展类
在 Django 中, 使用 Django-cors-headers 扩展类来解决跨域问题.

作用:
解决 django 开发中遇到的跨域访问资源问题
django-cors-headers 的安装和配置

# 安装 django-cors-headers 解决跨域问题:
# 1.安装 django-cors-headers
pip install django-cors-headers

# 2. 注册
INSTALLED_APPS = (
    ...
    # 添加 django-cors-headers 的配置内容, 使其可以进行cors跨域
    'corsheaders',
    ...
)

# 3.中间件
MIDDLEWARE = [
    # 添加 django-cors-headers 的配置内容, 使其可以进行cors跨域
    'corsheaders.middleware.CorsMiddleware',
    ...
]

# 4.添加白名单
# 凡是出现在白名单中的域名,都可以访问后端接口
# 添加 django-cors-headers 的白名单, 使白名单中的 host 可以进行跨域请求
CORS_ORIGIN_WHITELIST = (
    # 白名单:
    "http.xxx.xxx.xxx
)
# 允许白名单中的 host 跨域请求时携带 cookie
CORS_ALLOW_CREDENTIALS = True


# CORS_ALLOW_CREDENTIALS 指明在跨域访问中,后端是否支持对cookie的操作。

你可能感兴趣的:(跨域请求,Django)