前后端开发的时候需要设置下跨域访问,设置如下
setting文件里添加
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
‘*’
)
CORS_ALLOW_METHODS = (
‘DELETE’,
‘GET’,
‘OPTIONS’,
‘PATCH’,
‘POST’,
‘PUT’,
‘VIEW’,
)
CORS_ALLOW_HEADERS = (
‘XMLHttpRequest’,
‘X_FILENAME’,
‘accept-encoding’,
‘authorization’,
‘content-type’,
‘dnt’,
‘origin’,
‘user-agent’,
‘x-csrftoken’,
‘x-requested-with’,
)
修改setting文件的 MIDDLEWARE ,注意要在CommonMiddleware前
MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
’corsheaders.middleware.CorsMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
]
修改ALLOWED_HOSTS = [’*’],也可以根据自己需求配置
在写request请求方法时加上csrf_exempt装饰器
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def post_data(request):
pass
即可实现跨域访问