前言
在Django服务器端写了一个API,返回JSON格式数据。前端登陆页面通过Ajax调用该API。
实例
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>login</title>
</head>
<body>
<body>
<div id="center">
<form id="Form" >
账号 <input type="text" id="adminName" class="adminname" name="phone" value="" /> <br />
密码 <input type="password" id="psw" class="pwd" name="password" value="" /> <br />
<input type="button" value="登陆" onclick="testAjax()" />
</form>
</div>
<script src="js/ajax.js"></script>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</body>
</html>
ajax.js
function testAjax() {
var adminName = document.getElementById('adminName').value;//获取html表单中adminName输入域对象的值,既账号
var psw = document.getElementById('psw').value;
var user={
phone:adminName,
password:psw,
};
$.ajax({
type:'POST',
data:JSON.stringify(user),
contentType :'application/json',
dataType:'json',
url :'api地址',
success :function(result){
if (result.status=="true"){
//输出响应的message信息
alert(result.message)
}else{
alert(result.message)
}
},
error: function(xmlHttpRequest, textStatus, errorThrown){
alert("请求对象XMLHttpRequest: "+XMLHttpRequest);
alert("错误类型textStatus: "+textStatus);
alert("异常对象errorThrown: "+errorThrown);
}
});
}
结果报错了。
错误信息:
Access to XMLHttpRequest at '服务器地址' from origin 'http://127.0.0.1:8848' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
原因
这是由于ajax跨域访问引起的。所谓跨域就是,在www.aaa.com域下,访问www.bbb.com域下的资源;出于安全的考虑浏览器允许跨域写,而不允许跨域读,写就是上行(发送请求send reques),读就是下行(接受响应receive response)。
解决方法
- 临时解决方法: 给chrome浏览器添加参数
打开cmd命令进入chrome浏览器目录,执行以下命令
chrome.exe --disable-web-security --user-agent="Android" --user-data-dir="C:/temp-chrome-eng
mac系统
open -a Google\ Chrome --args --disable-web-security --user-data-dir="/Users/thantshweaung/Documents/Project/ionic/chrome_cache"
- 永久解决方法:安装django-cors-headers
pip install django-cors-headers
在settings.py中增加:
INSTALLED_APPS = (
...
'corsheaders',
...
)
...
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware' ,
'django.middleware.common.CommonMiddleware' ,
...
]
CORS_ORIGIN_ALLOW_ALL = True
django-cors-headers详见:https://github.com/ottoyiu/django-cors-headers/