安装 pip3 install -i https://pypi.douban.com/simple django-cors-headers 注册App INSTALLED_APPS = [ ... ‘ app01.apps.App01Config ‘ , ‘ corsheaders ‘ , # 将 corsheaders 这个APP注册 ] 添加中间件 必须放在最前面,因为
安装
pip3 install -i https://pypi.douban.com/simple django-cors-headers
注册App
INSTALLED_APPS = [ ... ‘app01.apps.App01Config‘, ‘corsheaders‘, # 将 corsheaders 这个APP注册 ]
添加中间件
必须放在最前面,因为要先解决跨域的问题。只有允许跨域请求,后续的中间件才会正常执行。
MIDDLEWARE = [ ‘corsheaders.middleware.CorsMiddleware‘, # 添加中间件 ‘django.middleware.security.SecurityMiddleware‘, ‘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‘, ]
配置
你可以选择不限制跨域访问
CORS_ORIGIN_ALLOW_ALL = True
或者你可以选择设置允许访问的白名单
CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( # ‘<YOUR_DOMAIN>[:PORT]‘, ‘127.0.0.1:8080‘ )