Vite代理下获取真实请求的URL

2023年09月18日

在使用 vite 进行本地代理的时候,真实请求的地址会被本地代理转发,平时开发我们使用 chrome dev tools 的时候,也是没法看到这个真实地址,不方便进行定位,

我们可以通过 vite 里的一个 bypass 函数来实现定位

 server: {
     proxy: {
       '/api': {
         target: 'http://localhost:8050',
         changeOrigin: true,
         ws: true,
         rewrite: (path) => { 
           return path.replace(new RegExp(`^/api`), '')
         },
         bypass(req,res, options){
           const proxyUrl = new URL( options.rewrite(req.url) || '', (options.target) as string)?.href || '';
           console.log(proxyUrl);
         }
         // only https
         // secure: false
       },

这样就可以通过控制台查看,当然也可以将这个 url 写入到 header,那么在实际用 chrome 调试的时候会更加直观了。

© 1987 - 2023 张晓刚 版权所有

浙ICP备16002143号-1