安装第三方跨域包:django-cors-headers
解决:
- 基本的跨域请求能够实现;
- 能够获取跨域请求返回的响应头中的所有字段(默认只返回Content-Type);
- 能够发起跨域请求的时候携带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);
}
});
});