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

Next.js + Prisma动态路由传参报错:期望Int类型却传入String

错误原因及解决办法

核心错误点

  1. getUserById函数未返回查询结果:函数内部查询到post后未返回值,导致调用时解构{post}获取到undefined,同时可能掩盖真实类型问题。
  2. ID转换存在失效风险:parseInt遇到非数字字符会返回NaN,而NaN并非有效整数类型,传递给Prisma时触发类型错误;且未指定parseInt的基数参数,可能引发意外进制转换。
  3. 缺少ID有效性校验:未提前校验转换后的ID是否为有效整数,直接传递给Prisma引发错误。

修复步骤

1. 修正数据查询函数

确保函数返回查询结果,并添加ID有效性校验:

export async function getUserById(id){
  // 校验ID是否为有效整数
  if (isNaN(id) || !Number.isInteger(id)) {
    throw new Error("无效的文章ID");
  }
  
  const post = await prisma.post.findUnique({
    where:{
        id
    }
  });
  
  // 返回包含post的对象,匹配调用时的解构语法
  return { post };
}

2. 完善动态路由页面的ID处理

添加转换后的ID校验,处理无效ID的情况:

const page = async ({params}) => {
  // 使用parseInt并指定基数10,避免八进制解析问题
  const id = parseInt(params.postId, 10);
  
  // 校验ID是否有效
  if (isNaN(id)) {
    return <div>无效的文章ID</div>;
  }
  
  try {
    const {post} = await getUserById(id);
    
    return (
      <div>
        {post ? (
          <>
            <h2>{post.title}</h2>
            <p>{post.content}</p>
            <span>发布日期:{post.date}</span>
          </>
        ) : (
          <div>未找到对应文章</div>
        )}
      </div>
    );
  } catch (err) {
    console.error(err);
    return <div>获取文章失败</div>;
  }
};

3. 额外检查点

  • 确认Prisma Schema已同步到客户端:运行npx prisma generate确保模型定义的类型更新到客户端代码。
  • 检查动态路由文件名是否正确(如[postId].js或[postId].tsx),确保params.postId能正确获取路由参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:16