美文网首页
如何在控制台显示devServer配置proxy代理的真实url

如何在控制台显示devServer配置proxy代理的真实url

作者: NanaCti | 来源:发表于2023-08-21 18:39 被阅读0次
image.png
  • 项目中配置proxy的配置为
    devServer: {
      port: 8080,
      proxy: {
        "/api": {
          target: "http://xxx:3000",
          ws: true,
          changeOrigin: true,
          pathRewrite: {
              "^/api": "",
          },
      },
      hot: true,
    }
  • 新增一个onProxyRes方法
   const onProxyRes = (proxy) => {
    for (const api in proxy) {
      const {target, ws, changeOrigin, pathRewrite} = proxy[api];
      proxy[api] = {
        target,
        ws: ws || false,
        changeOrigin: changeOrigin || false,
        pathRewrite: pathRewrite || undefined,
        onProxyRes(proxyRes, req) {
          try {
            const targetObj = new URL(target)
            let reqUrl = req.url
            if (pathRewrite) {
              for (const key in pathRewrite) {
                const replaceValue = pathRewrite[key];
                let pattern = new RegExp(key)
                reqUrl = req.url.replace(pattern, replaceValue)
              }
            }
            let pathname = (targetObj.pathname + reqUrl).replace('//', '/')
            const realUrl = new URL(pathname, targetObj.origin)?.href ?? ''
            proxyRes.headers['x-real-url'] = realUrl
          } catch (error) {
            proxyRes.headers['x-real-url'] = 'undefined'
          }
        }
      }
    }
    return proxy
  }
  • 修改proxy配置
    devServer: {
      port: 8080,
      proxy: onProxyRes({
        "/api": {
          target: "http://xxx:3000",
          ws: true,
          changeOrigin: true,
          pathRewrite: {
              "^/api": "",
          },
      }),
      hot: true,
    }

相关文章

网友评论

      本文标题:如何在控制台显示devServer配置proxy代理的真实url

      本文链接:https://www.haomeiwen.com/subject/igkymdtx.html