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

Express接口报错Cannot GET /api/movies/1,请求定位修复问题

问题排查与修复方案

核心错误点

  • 路由路径缺失开头斜杠:app.get("api/movies/:id") 未以/开头,Express无法匹配/api/movies/1这类路径,必须改为/api/movies/:id。
  • 回调参数名不匹配:路由回调中使用request作为请求参数,但内部写的是req.params.id,参数名不一致会导致报错,需统一参数名(比如都用req和res)。
  • 未实现ID匹配电影的逻辑:当前代码仅返回字符串,需添加根据ID查找对应电影对象的逻辑。
  • 变量定义顺序不合理:movies数组定义在路由之后,虽JS有变量提升,但建议将数据定义放在路由前,逻辑更清晰。

修正后的完整代码

const express = require("express");
const app = express();
const port = 5050;

// 提前定义电影数据,确保路由能正常访问
const movies = [
  {
    id: 1,
    title: "Citizen Kane",
    director: "Orson Wells",
    year: "1941",
    colors: false,
    duration: 120,
  },
  {
    id: 2,
    title: "The Godfather",
    director: "Francis Ford Coppola",
    year: "1972",
    colors: true,
    duration: 180,
  },
  {
    id: 3,
    title: "Pulp Fiction",
    director: "Quentin Tarantino",
    year: "1994",
    color: true,
    duration: 180,
  },
];

app.get("/", (req, res) => {
  res.send("Welcome to my favourite movie list");
});

app.get("/api/movies/", function (req, res) {
  res.status(200).json(movies);
});

app.get("/api/movies/:id", function (req, res) {
  // 将URL参数转为数字,匹配movies中的数字类型id
  const movieId = parseInt(req.params.id);
  // 查找对应ID的电影
  const targetMovie = movies.find(item => item.id === movieId);
  
  if (targetMovie) {
    res.status(200).json(targetMovie);
  } else {
    // 找不到对应电影时返回404状态
    res.status(404).send("Movie not found");
  }
});

app.listen(port, (err) => {
  if (err) {
    console.error("Something bad happened");
  } else {
    console.log(`Server is listening on ${port}`);
  }
});

修复说明

  1. 修正路由路径后,Express可正确匹配/api/movies/1这类带ID的请求。
  2. 统一回调参数名,避免参数未定义的报错。
  3. 添加电影查找逻辑:将URL参数转为数字后,用Array.find()匹配对应ID的电影,找到则返回JSON格式的电影对象,找不到则返回404状态和提示。
  4. 调整数据定义位置,让代码逻辑更连贯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:35:18