解决跨域请求问题可以从前端解决也可以通过配置后台解决,通过配置后台允许跨域可以解决前端的一些麻烦。Django通过中间件实现允许跨域。
1.安装django-cors-headers中间件
pip install django-cors-headers
2.配置settings文件
INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 注意顺序 ... ) #跨域增加忽略 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', 'Pragma', )