app.use(function(req, res, next) { console.log('hostname:' + req.hostname) var allowOrigins = [ 'http://www.linyqiang.com', "http://localhost:3000", 'http://192.168.1.101:3000' ]; var origin = req.headers.origin; if (allowOrigins.indexOf(origin) > -1 || /(\b|.*\.)linyqiang.com$/.test(origin) === true) { // 如果req.headers.origin 在 allowOrigin 里面,则指定origin可以跨域 res.setHeader('Access-Control-Allow-Origin', origin); } else { res.setHeader('Access-Control-Allow-Origin', '*'); } res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Methods', 'GET,PUT,DELET,POST'); res.header('Access-Control-Allow-Headers', 'Content-Type,x-access-token,Access-Control-Allow-Headers, Authorization, X-Requested-With'); next(); })
分开指定
和res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Origin', '*');
是因为有部分origin我希望能够使用withCredentials: true
的方式发送cookie等信息。 如果简简单单的设置’ * ‘
的话,客户端
fetch(url, { withCredentials: true, // 无效,chrome会拦截 mode: 'cors' })
并且使用这种方式, 也会避免cookie 和session 跨域问题