chrome会报这个错误:
Refused to get unsafe header
解决方案:
服务器脚本,比如php控制器init函数里面加入
header('Access-Control-Allow-Origin:http://xxx.com');
header('Access-Control-Allow-Methods:POST'); // 响应类型
header('Access-Control-Allow-Headers:x-requested-with,content-type,authcode'); // 响应头设置
header('Access-Control-Expose-Headers: xxx自定义头字段');//important
前端代码
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
/* $.ajax({
type: "POST",
url: "http://api.com/auth/sign-in",
data:{"email":"xxx@qq.com","password":"123456"},
dataType: "json",
success: function(data,textStatus, request) {
//console.log(data);
console.log(textStatus);
var obj = request.getResponseHeader("xxx自定义字段");//["content-type"]
console.log(obj);
}
});*/
var xhr = new XMLHttpRequest();
xhr.withCredentials = true; //solution : Refused to get unsafe header in chrome,server setting : header('Access-Control-Expose-Headers: authcode');
xhr.open('post', 'http://test.com/auth/sign-in',true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onload = function () {
console.log('load:', xhr.getAllResponseHeaders());
console.log(xhr.getResponseHeader('xxx自定义字段'));
console.log('=================================')};
var data = "email=xxx@qq.com&password=123456";
xhr.send(data);
});
})
</script>
</head>
<body>
<button>test</button>
</body>
</html>