You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite代理rewrite函数异常:添加return才生效的原因咨询

问题:Vite代理rewrite函数写法差异导致的代理异常

我通过以下方法创建基于.env.development中定义的不同前缀的代理列表:

/**
 * Generate proxy
 * @param list
 */
export function createProxy(list: ProxyList = []) {
  const ret: ProxyTargetList = {};
  for (const [prefix, target] of list) {
    const isHttps = httpsRE.test(target);

    ret[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
      ...(isHttps ? { secure: false } : {}),
    };
  }
  console.log('proxy list');
  console.log(ret);
  return ret;
}

.env.development中的代理配置如下:

VITE_PROXY = [["/basic-api","http://127.0.0.1:3100"],["/api","http://127.0.0.1:8080"],["/upload","http://localhost:3300/upload"]]

但当我请求http://127.0.0.1/api/xxx时,并未按预期重写为http://127.0.0.1:8080/xxx。之后我将rewrite函数修改为如下形式,代理就正常工作了:

rewrite: (path) => 
        {path.replace(new RegExp(`^${prefix}`), '');return path},

我对此感到困惑,常规Vite代理rewrite写法无需添加return语句,请问这两种写法的差异是什么?


解答

核心差异在于箭头函数的两种语法规则,以及它们对路径重写的实际影响:

  1. 第一种写法(简洁箭头函数)

    rewrite: (path) => path.replace(new RegExp(`^${prefix}`), '')
    

    这是箭头函数的简洁语法,会自动返回path.replace()的执行结果。replace方法会生成一个去掉前缀(比如/api)的新字符串,所以代理后的路径会变成目标地址+新路径,也就是http://127.0.0.1:8080/xxx。

  2. 第二种写法(块级箭头函数)

    rewrite: (path) => {path.replace(new RegExp(`^${prefix}`), '');return path}
    

    这是箭头函数的块级语法,必须显式写return才会返回值。这里你执行了path.replace()但没有保存结果(JS字符串是不可变的,replace不会修改原字符串),最后直接返回了原path,相当于没有做任何路径重写,代理后的路径是http://127.0.0.1:8080/api/xxx。

你遇到的情况刚好反过来,说明你的后端接口本身是包含/api前缀的——第一种写法去掉前缀后,后端找不到对应接口;第二种写法保留原路径,才匹配上了后端的接口。


内容的提问来源于stack exchange,提问作者Jeffrey Yang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:45:32