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

无法连接Prisma Server且创建食谱失败,寻求技术帮助

解决Prisma创建食谱时无法获取响应的问题

我来帮你梳理下代码里的几个关键问题,这些问题直接导致你无法正常获取Prisma的响应:

1. 重复发送HTTP响应

你在循环的每一次prisma.createRecipes的then回调里都调用了res.json(response),但HTTP响应只能发送一次。第一次调用res.json后,整个请求的响应就已经结束,后续再调用会触发Cannot set headers after they are sent to the client的错误,这会导致后续Prisma操作的结果无法正常返回,甚至让整个请求异常中断。

2. 未正确处理异步操作的并发

循环中直接调用prisma.createRecipes是异步操作,但你没有等待这些操作全部完成就结束了函数。这会导致部分数据库操作可能还没执行完,请求就已经提前结束,而且出现错误时也无法正确传递给前端。

3. Prisma方法名可能存在错误

通常Prisma的模型如果是单数Recipe,创建单个实例的方法应该是createRecipe,复数的createRecipes一般对应createMany(用于批量创建)。如果你的模型定义是Recipe,那这里的方法名可能写错了,这也会直接导致调用失败。


修复后的代码

下面是修正后的版本,解决了上述所有问题:

exports.createRecipe = async (req, res, next) => { 
  const recipes = req.body;
  try {
    // 使用Promise.all等待所有创建操作完成
    const results = await Promise.all(recipes.map(rec => {
      const { name, description, imgUrl, ingredient } = rec;
      // 注意:如果模型是Recipe,这里应该是createRecipe,不是createRecipes
      return prisma.createRecipe({ 
        name, 
        description, 
        imgUrl, 
        ingredients: { create: ingredient } 
      });
    }));
    // 所有操作完成后统一发送响应
    res.status(201).json(results);
  } catch (error) {
    console.error(error);
    // 将错误传递给后端的错误处理中间件
    next(error);
  }
};

额外的优化建议

  • 如果你的Prisma版本支持createMany,可以考虑用批量创建提升性能,但注意createMany不支持嵌套创建关联数据(比如你这里的ingredients),所以如果需要同时创建关联数据,还是得用上面的方式。
  • 前端发送的JSON要确保所有键都是双引号(你提供的示例里用了单引号,实际发送时要修正,否则后端可能解析失败):
[ 
  { 
    "name": "MY first Recipe", 
    "description": "Test Recipe", 
    "imgUrl": "http://www.google.com",
    "ingredient": [{"name": "Apple", "amount": "2"}, {"name": "Tomatoes", "amount": "3"}] 
  }, 
  { 
    "name": "MY first Recipe", 
    "description": "Test Recipe", 
    "imgUrl": "http://www.google.com",
    "ingredient": [{"name": "Apple", "amount": "2"}, {"name": "Tomatoes", "amount": "3"}] 
  } 
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:37:35