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

Express.js GET请求URL拼接报错及格式优化问题求助

问题解决:生成正确格式的请求URL并避免报错

问题原因分析

  • urltemp2生成多余斜杠:window.location.pathname通常以/开头(比如/result=value1),用replace("result=", "")会得到/value1,拼接后传入getRequest就会变成result=/value1&myvar,导致result=后出现多余的/。
  • urltemp1报错:当当前路径不包含/result=时,replace("/result=", "")会返回原路径(比如/),后续拼接逻辑可能引发未定义属性访问错误;另外如果路径格式不符合预期,也可能导致后续处理出错。

解决方案

通过正则表达式精准提取result=后的内容,避免多余斜杠,同时兼容首次访问或路径不含result=的场景:

// myvar是6位数字
// serverURL为服务器IP地址,例如192.168.666.666:5000/

// 提取当前路径中result=后面的有效内容,忽略开头的/
const pathMatch = window.location.pathname.match(/^\/?result=(.*)$/);
// 若匹配到内容则取出,否则设为空字符串
const existingParams = pathMatch ? pathMatch[1] : '';
// 拼接新参数:已有参数则用&连接,无参数则直接使用myvar
const urltemp = existingParams ? `${existingParams}&${myvar}` : myvar;

getRequest(urltemp);

async function getRequest(desc) {
    const searchUrl = "result=";
    try {
        const response = await fetch(serverURL + searchUrl + desc, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        });
        if (!response.ok) {
            throw new Error("HTTP status " + response.status);
        }
        const res = await response.json();
        nextFunc(res);
        window.history.pushState(null, null, `result=${desc}`);
    } catch (error) {
        console.log(error);
    }
}

代码说明

  1. 正则匹配:/^\/?result=(.*)$/可以匹配以/result=或result=开头的路径,捕获result=之后的所有内容,避免前导/被带入参数。
  2. 参数拼接逻辑:根据是否已有参数决定是否添加&,确保参数格式正确。
  3. 简化异步逻辑:将then链改为async/await的try/catch结构,代码更清晰易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:50:51