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

Next.js router.push查询参数编码问题:如何传递未编码逗号?

解决router.push传递含逗号参数时自动编码的问题

直接用query对象传参时,Next.js的router.push会自动对特殊字符做URL编码,这是符合URL规范的行为,但如果业务上需要保留逗号不编码,可以试试下面两种方法:

  • 手动拼接URL字符串
    放弃使用query配置项,直接构造完整的URL路径,手动控制参数的编码逻辑:

    const newQuery = { ...router.query, pets: 'cats,dogs' };
    // 构造查询字符串:只编码key,value保留原格式
    const searchStr = Object.entries(newQuery)
      .map(([key, val]) => `${encodeURIComponent(key)}=${val}`)
      .join('&');
    // 拼接后跳转
    router.push(`${router.pathname}?${searchStr}`);
    
  • 替换编码后的字符
    先用URLSearchParams处理参数,再把编码后的%2C替换回逗号:

    const newQuery = { ...router.query, pets: 'cats,dogs' };
    const searchParams = new URLSearchParams(newQuery).toString().replace(/%2C/g, ',');
    router.push(`${router.pathname}?${searchParams}`);
    

⚠️ 注意:虽然这样能得到myurl?pets=cats,dogs的URL,但要确认后端服务能正确解析带逗号的参数——部分后端框架会默认把逗号当作参数值的分隔符,可能导致解析错误,需要提前确认后端处理逻辑。

内容的提问来源于stack exchange,提问作者Muhsin Ummer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:28:13