Django 1.x 版本修改一些配置的名称,如:
版本 | settings.py 中间件名称 |
---|---|
2.x | MIDDLEWARE |
1.x | MIDDLEWARE_CLASSES |
设置跨域请求的时候要注意
域名,协议,端口不同。浏览器执行javascript脚本时,不会被执行。
django-cors-headers
django-cors-headers
2.修改 setting.py
INSTALLED_APPS = [
...
'corsheaders',
...
]
# 添加中间件
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',# 默认
'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',
)
#部署到云服务上必备
ALLOWED_HOSTS = ['*']
本例 ajax
请求示例代码
<html>
<head>
<meta charset="UTF-8">
<title>title>
head>
<script src="js/jquery-1.7.2.js">script>
<script type="text/javascript">
function upd() {
$.ajax({
type: "GET",
data: "a=1",
url: "http://127.0.0.1:8000/books/?format=json",
success: function(result) {
console.log(result);
//alert(result)
}
});
}
script>
<body>
<button id="btn2" onclick="upd()">Get request 获取button>
body>
html>
django解决跨域请求的问题