跨域问题
前端
......
后端
Python解决
方式一: 局部使用
res['Access-Control-Allow-Origin'] = '*'
def index(request): # 写一个接口
user = models.User.objects.all() # 获取用户数据
data = json.dumps(user) # 将数据转成 json 格式
res = JsonResponse(data) # 序列化数据
res['Access-Control-Allow-Origin'] = '*' # 解决跨域问题
return res
方式二: 全局使用
1. 下载模块
pip3 install django-cors-headers
2. app中注册
INSTALLED_APPS = (
...
'corsheaders',
...
)
3. 中间件注册
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
4. 把下面的复制到配置文件中
CORS_ORIGIN_ALLOW_ALL = True
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',
)