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

React项目中通过Params获取单条详情失败,Postman无响应

问题分析与解决方案

1. 修正请求路径

你的recipesRouter在主文件中挂载到了/recipes路径下,路由文件中定义的/createrecipe/:id会被拼接为/recipes/createrecipe/:id。

正确的Postman请求地址:
GET http://localhost:3001/recipes/createrecipe/1

2. 检查数据库查询字段

若路径修正后仍无数据返回,需确认RecipeModel的主键字段:

  • Mongoose默认主键为_id(ObjectId类型),而非id。如果使用MongoDB自动生成的主键,需将查询条件改为_id,并将字符串ID转换为ObjectId:
import { ObjectId } from "mongoose";

router.get("/createrecipe/:id", async (req, res) => {
  try {
    const result = await RecipeModel.findOne({ _id: new ObjectId(req.params.id) });
    if (result) {
      res.json(result);
    } else {
      res.status(404).json({ message: 'no recipe' });
    }
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});
  • 若模型自定义了id字段(字符串/数字类型),需确认数据库中文档的id值是否为1,保证查询条件匹配。

3. 优化响应格式与错误处理

建议返回JSON格式响应,并添加异常捕获,避免服务器崩溃:

router.get("/createrecipe/:id", async (req, res) => {
  try {
    // 根据实际字段调整查询条件
    const result = await RecipeModel.findOne({ _id: new ObjectId(req.params.id) });
    result ? res.json(result) : res.status(404).json({ message: 'no recipe found' });
  } catch (error) {
    res.status(500).json({ error: 'Server error', details: error.message });
  }
});

4. React前端请求路径修正

前端发送请求时需使用正确路径,示例:

const fetchRecipeDetail = async (id) => {
  const response = await fetch(`http://localhost:3001/recipes/createrecipe/${id}`);
  return await response.json();
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:05:06