Nodejs跨域
如果需要开方跨域访问
module.exports = function allowCrossDomain(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'X-Requested-With, Content-Type, Content-Length, Authorization, Accept'
);
// intercept OPTIONS method
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
};
如果不用中间件, 直接手撸那么是这样的:
//跨域会引起一次option
if('OPTIONS'===req.method){
res.writeHead(200, {
'Content-Type': type,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers':
'X-Requested-With, Content-Type, Content-Length, Authorization, Accept',
});
res.end();
}
//然后再你真正要跨域的方法里面也这么写head