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

2023-08-21  本文已影响0人  NanaCti
image.png
    devServer: {
      port: 8080,
      proxy: {
        "/api": {
          target: "http://xxx:3000",
          ws: true,
          changeOrigin: true,
          pathRewrite: {
              "^/api": "",
          },
      },
      hot: true,
    }
   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
  }
    devServer: {
      port: 8080,
      proxy: onProxyRes({
        "/api": {
          target: "http://xxx:3000",
          ws: true,
          changeOrigin: true,
          pathRewrite: {
              "^/api": "",
          },
      }),
      hot: true,
    }
上一篇下一篇

猜你喜欢

热点阅读