vue axios node cors 跨域解决 session验证

时间:2025-03-09 19:55:33


方法一:node 端配置 中


app.use('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8070'); //这个表示任意域名都可以访问,这样写不能携带cookie了。
  res.header('Access-Control-Allow-Credentials', true); // 允许服务器端发送Cookie数据
//('Access-Control-Allow-Origin', ''); //这样写,只有 可以访问。
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');//设置方法
  if (req.method == 'OPTIONS') {
    res.send(200); // 意思是,在正常的请求之前,会发送一个验证,是否可以请求。
  }
  else {
    next();
  }
});
vue 中是用axios 进行ajax请求 需要对axios 配置 发送cookie 为true

axios.defaults.withCredentials = true

方法二:cors模块

node端配置为

var cors = require('cors');
app.use(cors({
  origin: 'http://localhost:8070',
  credentials: true  // 是否带cookie
}));
vue axios设置

axios.defaults.withCredentials = true


/x-radish/p/

/xuange306/p/


/TroyGoode/node-cors