当我们跨域使用自定义Header的时候,前端会发出两次HTTP请求,第一次类型为OPTION,以向后端验证“跨域中哪些Header可以拥有正常访问权限”,然后,才会发出真正的第二次HTTP请求。第一次,可以看到类型为OPTION,并且没有我们需要的自定义Header:
前端代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.test{
width: 100px;
height: 100px;
background: green;
}
</style>
</head>
<body>
<button οnclick="aa()">111</button>
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function aa(){
//alert();
var dataK = {"a":"1111"}
$.ajax({
headers: {
"xtoken":"12123132",
"xcookie":'1313212314564645646545464654646464646546',
"Content-Type":"application/json",
"Cookie":'12312312132'
},
type: 'post',
//dataType: "json",
//contentType: "application/json",
xhrFields:{withCredentials:true},//设置跨域传递cookie
data:JSON.stringify(dataK),
url: 'http://127.0.0.1:3000/',
//data: {textName:'123123123'},
success: function(data) {
console.log("----data:------");
alert(data);
},
error: function(err) {
},
complete: function(XMLHttpRequest, status) {
//alert()
}
});
}
</script>
</body>
</html>
node代码如下
var connect = require('connect');
var cookieParser = require('cookie-parser');
console.log(connect);
var app = connect()
.use(cookieParser('tobi is a cool ferret'))
.use(function(req,res,next){
//console.log(req.cookies);
//console.log(req.authorization);
//console.log(req.signedCookies);
//console.log(req);
next();
})
.use(hello)
.listen(3000);
/* function logger(req, res, next) {
console.log('%s %s', req.method, req.url);
//console.log(req);
next();
} */
function hello(req, res) {
//console.log(req);
console.log(req.headers.origin);
console.log(req);
res.setHeader('Content-Type','application/json');
res.setHeader('charset','utf-8');
res.setHeader('aaaa','foo=bar');
res.setHeader('Set-Cookie','111111');
res.setHeader('Access-Control-Allow-Origin',req.headers.origin);
res.setHeader('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS'); //跨域请求AJAXA会发送两次 第一次 是OPTION 第二次才是真正的POST
res.setHeader('Access-Control-Allow-Headers','X-Requested,xtoken,xcookie,Content-Type');//默认让前端可以带这些请求头
res.setHeader('Access-Control-Allow-Credentials','true');// 默认可以让跨域传递COOKie
//res.setHeader('Access-Control-Allow-Hea d ers','X-Requested,xcookie');
//res.setHeader('aaabbb','');
res.end('hello world');
}