当我们跨域使用自定义Header的时候,前端会发出两次HTTP请求,第一次类型为OPTION,以向后端验证“跨域中哪些Header可以拥有正常访问权限”,然后,才会发出真正的第二次HTTP请求。第一次,可以看到类型为OPTION,并且没有我们需要的自定义Header:
前端代码如下:
.test{
width: 100px;
height: 100px;
background: green;
}
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');
}