如何通过安装django-cors-headers模块解决Django项目的跨域资源共享问题?
- 内容介绍
- 文章标签
- 相关推荐
本文共计218个文字,预计阅读时间需要1分钟。
安装pip3并安装django-cors-headers,然后在App配置中注册:
pythonpip3 install -i https://pypi.douban.com/simple django-cors-headersAppConfig.INSTALLED_APPS=['app01.apps.App01Config', 'corsheaders']
安装
pip3 install -i 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‘ )
本文共计218个文字,预计阅读时间需要1分钟。
安装pip3并安装django-cors-headers,然后在App配置中注册:
pythonpip3 install -i https://pypi.douban.com/simple django-cors-headersAppConfig.INSTALLED_APPS=['app01.apps.App01Config', 'corsheaders']
安装
pip3 install -i 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‘ )

