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

ExpressJS模拟后端:配置/executions/executionId路由及解决路由匹配错误

解决ExpressJS中/executions/:executionId路由匹配错误并完成数据查询配置

我来帮你搞定这个问题!你遇到的Cannot match any routes. URL Segment: 'executions/190'错误,核心原因是路由定义的格式不对——你需要用动态参数语法来匹配可变的executionId值,而不是写死成固定的路径。下面是一步步的解决方案:

1. 先修正路由定义的核心问题

Express里要匹配动态路径参数,必须在参数名前加冒号:。比如你要匹配/executions/190、/executions/191这类路径,路由应该写成/executions/:executionId,而不是/executions/executionId(后者只会匹配/executions/executionId这个固定路径,自然找不到190的请求)。

2. 完整的Express后端实现代码

下面是包含路由配置、读取data.json并返回对应数据的完整代码:

const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 3000;

// 读取data.json数据(这里用同步读取,也可以改成异步的fs.readFile)
const getExecutionsData = () => {
  const dataPath = path.join(__dirname, 'data.json');
  const rawData = fs.readFileSync(dataPath, 'utf8');
  return JSON.parse(rawData);
};

// 配置动态路由:根据executionId查询对应数据
app.get('/executions/:executionId', (req, res) => {
  try {
    // 获取路径参数,注意转成数字(因为data里的executionId是数字类型)
    const targetId = parseInt(req.params.executionId, 10);
    const { singleExecutions } = getExecutionsData();
    
    // 查找匹配的执行记录
    const execution = singleExecutions.find(item => item.executionId === targetId);
    
    if (execution) {
      res.status(200).json(execution);
    } else {
      // 没找到对应记录时返回404
      res.status(404).json({ message: `Execution with ID ${targetId} not found` });
    }
  } catch (error) {
    // 处理读取文件或解析错误
    res.status(500).json({ message: 'Server error', error: error.message });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

3. 验证路由是否正常工作

启动你的Express服务后,用以下方式测试:

  • 在浏览器访问http://localhost:3000/executions/190,应该返回{"executionId":190, "label":"exe_190"}
  • 用curl命令测试:curl http://localhost:3000/executions/191,会得到对应的191号记录
  • 如果请求一个不存在的ID,比如/executions/999,会返回404的错误提示

4. 额外排查要点

如果还是遇到路由匹配问题,可以检查这几点:

  • 确认你的Express服务确实在运行,没有启动失败
  • 确认data.json文件的路径正确,放在和Express入口文件同级的目录下(或者调整getExecutionsData里的路径)
  • 确认请求的URL没有拼写错误,比如有没有多写斜杠(比如/executions//190)或者大小写问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:45:02