Django 用户认证 用户 邮箱登录 邮箱注册 ORM or,and,not form.py FORM ModelForm Paginator 分页 HTMl JQuery 定位元素 ajax django切片 restfulapi 跨域 Ubantu Python Mysql Scrapy 爬虫 导出 Python读写 Pycharm 破解 session re sqlit3 生成式 其他 Prism 富文本 CSS Nginx 部署 请求头 抓包 协议 selenium Ubuntu 宝塔 AI Comfy-ui ollama dify open-webui Git docker
django-cors-headers的使用
张建行 2022年4月26日 22:30 44 文章标签: Django 跨域

安装第三方跨域包:django-cors-headers

解决:

  1. 基本的跨域请求能够实现;
  2. 能够获取跨域请求返回的响应头中的所有字段(默认只返回Content-Type);
  3. 能够发起跨域请求的时候携带Cookie(默认不允许带Cookie)
配置settings.py文件:
INSTALLED_APPS = [
‘corsheaders’,
]
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’,
]
设置为False,如果设置为True,则请求无法携带Cookie了。
CORS_ORIGIN_ALLOW_ALL = False
设置请求是否允许携带Cookie,必须和xhrFields: {withCredentials: true,}同时使用。
CORS_ALLOW_CREDENTIALS = True
跨域源的白名单,需要跨域的源设置在这里
CORS_ORIGIN_WHITELIST = [
‘localhost:63342’,
]
指定哪些方法可以发送跨域请求
CORS_ALLOW_METHODS = (
‘DELETE’,
‘GET’,
‘OPTIONS’,
‘PATCH’,
‘POST’,
‘PUT’,
)
指定请求头中允许携带的字段
CORS_ALLOW_HEADERS = (
‘accept’,
‘accept-encoding’,
‘authorization’,
‘content-type’,
‘dnt’,
‘origin’,
‘user-agent’,
‘x-csrftoken’,
‘x-requested-with’,
‘cookie’,
)
后台views.py配置:
class StudentInspectView(View):
“”"
检查学员学号是否唯一的CBV视图类接口。
“”"
def post(self, request):
stu_id = request.POST.get(‘sid’)
data = {}
if StuModel.objects.filter(id=stu_id):
# 学号已经存在
data[‘is_exist’] = 1
data[‘message’] = ‘该学号已经存在’
else:
data[‘is_exist’] = 0
data[‘message’] = ‘该学号可以使用’
# 需要返回Response对象
return JsonResponse(data)
前端js配置:
// 检查学号是否已经存在
$(’#sid’).blur(function () {
//在数据没有合法之前,“提交按钮” 不能点击;
$(’#add’).attr(‘disabled’, true);
$.ajax({
url: ‘http://localhost:8000/inspect/’,
type: ‘POST’,
data: {
‘sid’: $(’#sid’).val()
},
xhrFields: {
withCredentials: true
},
headers: {
‘X-CSRFToken’: $.cookie(‘csrftoken’),
},
success: function (data, status) {
$(’#sid’).next().text(data.message);
}
});
});