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

React请求Express后端/api/products/:id路由无法获取数据如何解决

问题修复方案

核心问题1:请求路径尾斜杠不匹配

你在detailsProduct方法中请求的路径末尾多了一个斜杠:

const res = await fetch(`/api/products/${productId}/`, {

Express默认严格区分路径末尾是否带斜杠,而你的路由定义是/api/products/:id,两者不匹配就会返回404。
修复方法:去掉路径末尾的斜杠

const res = await fetch(`/api/products/${productId}`, {

核心问题2:fetch响应未做状态判断

fetch只有在网络完全不通的情况下才会进入catch分支,只要服务器有返回(哪怕是404、500状态码)都会走正常逻辑,你现在如果接口返回404,不会触发失败回调,还会把错误信息当做正常数据返回。
修复方法:请求后增加响应状态判断

const res = await fetch(`/api/products/${productId}`, {
  method: "GET",
  headers: {
    "Content-Type": "Application/Json",
  },
});
// 新增状态判断
if (!res.ok) {
  throw new Error(res.statusText || "产品查询失败")
}
const data = await res.json();

问题3:listProducts方法存在两处隐患

你写的获取产品列表的方法有逻辑错误,属于潜在bug:

  1. 请求路径写错:用了单引号包裹模板字符串,且引用了不存在的productId变量,本应该请求全量产品路径
  2. 失败dispatch缺少type字段
    修复后的listProducts代码:
export const listProducts = () => async (dispatch) => {
  dispatch({ type: PRODUCT_LIST_REQUEST });
  try {
    const res = await fetch("/api/products", {
      method: "GET",
      headers: {
        "Content-Type": "Application/Json",
      },
    });
    // 同样建议加状态判断
    if (!res.ok) {
      throw new Error("产品列表查询失败")
    }
    const data = await res.json();
    console.log("Product Data : ", data);
    dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
  } catch (error) {
    // 补充缺失的type字段
    dispatch({ type: PRODUCT_LIST_FAILURE, payload: error });
  }
};

可选优化:findById写法简化

你在ProductRouter的/:id路由中Product.findById({ _id: id })可以简化为直接传id:

const all_products = await Product.findById(id);

剩余排查项

如果修改后还是无法正常返回,可以按以下顺序排查:

  • 打印后端接收到的req.params.id是否和前端传的productId一致,确认参数传递正常
  • 确认数据库中确实存在_id为6173d16a7037921b98ec9777的产品数据
  • 建议恢复dispatch({ type: PRODUCT_DETAILS_REQUEST, payload: productId });的注释,不然详情页的加载状态不会正常触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:27:02