webpack http-proxy-middleware为每个请求创建新会话

olhwl3o2  于 2023-05-29  发布在  Webpack
关注(0)|答案(1)|浏览(151)

我用http-proxy-middleware构建了一个代理,它为每个请求生成新的会话,因此我不能用会话中的令牌存储来验证登录状态。

1u4esq0p

1u4esq0p1#

// proxy middleware options 
var options = {
  target: 'http://localhost:8081', // target host 
  changeOrigin: true,               // needed for virtual hosted sites 
  ws: true,                         // proxy websockets 
  logLevel: "debug",
  pathRewrite: {
    '^/src/wxmservice/' : '/wxmservice/'
  },
  onProxyRes: function (proxyRes, req, res) {
    if (proxyRes.headers['set-cookie'] != undefined) {
        req.session['cookie'] = proxyRes.headers['set-cookie'];  // must be or you will get new session for each call
        req.session['proxy-cookie'] = proxyRes.headers['set-cookie'];  // add to other key because cookie will be lost
    }
    console.log("response: " + req.session.id);
    console.log(req.session);
  },
  onProxyReq: function (proxyReq, req, res) {
    // check for whether the session be freshed
    if (req.session.view)
      req.session.view ++;
    else
      req.session.view = 1;

    // use ower key to restore cookie
    if (req.session['proxy-cookie'] != undefined)
      proxyReq.setHeader('cookie', req.session['proxy-cookie'][0]);

    console.log("request: " + req.session.id);
    console.log(req.session);
  }
};

var session = require('express-session');
app.use(session({
    secret: 'sessiontest',
    resave: true,
    saveUninitialized:true
}));

相关问题