webpack-dev-server如何重定向?

下方代码在webpack-dev-server运行后会打开默认浏览器(Chrome)访问localhost:8080/login,这时根据配置代理到http://login.example.com进行登录,该地址登录后会进行302的跳转,下方代码将其set-cookie的值设置到cookieMap中并重定向回localhost:8080,之后调用api相关的请求均能正常带上cookie值。现在想模拟外网环境打开多个浏览器登录多个用户,但如在Firefox中打开localhost:8080由于没有登录所以调用api相关的请求均没有cookie值。如果在Firefox中打开localhost:8080/login则都正常,现在想减少输入,打开localhost:8080后,如何根据下方cookieMap中不存在当前浏览器的cookie值跳转到指定登录页localhost:8080/login,如存在则正常打开localhost:8080

const cookieMap = {};
module.exports = {
  devServer: {
    historyApiFallback: true,
    hot: true,
    inline: true,
    progress: true,
    openPage: 'login',
    proxy: [ {
      context: ['/api'],
      target: "http://api.example.com",
      changeOrigin: true,
      onProxyReq(proxyReq, req, res) {
        let cookie = cookieMap[req.get('User-Agent')] || '';
        proxyReq.setHeader('Cookie', cookie);
      }
    }, {
      context: ['/login'],
      target: "http://login.example.com",
      changeOrigin: true,
      onProxyRes(proxyRes, req, res) {
        if(proxyRes.statusCode === 302) {
          if(proxyRes.headers['set-cookie']) {
            cookieMap[req.get('User-Agent')] = proxyRes.headers['set-cookie'].join(';');
          }
          proxyRes.headers['Location'] = '/';
        }
      }
    }]
  }
}
阅读 11.7k
1 个回答

仔细阅读webpack-DevServer文档,可以发现发现配置中加入index: '',即可代理根目录,所以只需在代理中再配置一个根目录,代码如下

const cookieMap = {};
module.exports = {
  devServer: {
    index: '',// specify to enable root proxying
    historyApiFallback: true,
    hot: true,
    inline: true,
    progress: true,
    openPage: 'login',
    proxy: [ {
      context: ['/api'],
      target: "http://api.example.com",
      changeOrigin: true,
      onProxyReq(proxyReq, req, res) {
        let cookie = cookieMap[req.get('User-Agent')] || '';
        proxyReq.setHeader('Cookie', cookie);
      }
    }, {
      context: ['/login'],
      target: "http://login.example.com",
      changeOrigin: true,
      onProxyRes(proxyRes, req, res) {
        if(proxyRes.statusCode === 302) {
          if(proxyRes.headers['set-cookie']) {
            cookieMap[req.get('User-Agent')] = proxyRes.headers['set-cookie'].join(';');
          }
          proxyRes.headers['Location'] = '/';
        }
      }
    }, {
      context: ['/'],
      bypass: function(req, res, proxyOptions) {
        if (req.url === '/' && !cookieMap[req.get('User-Agent')]) {
          res.redirect('/login');
          return true;
        }
      }
    }]
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏