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

Next.js13.4动态路由无法显示内容,请求问题排查

解决Next.js 13.4动态路由无法展示文章的问题

核心问题分析

  • 你的api/content/route.ts中所有文章的slug均为ejcerc-334,不存在与访问路径loremIpsum匹配的条目,导致posts.find()无法找到对应文章,最终post为undefined,页面无内容渲染。
  • 使用非空断言!强制认定post存在,会在找不到文章时抛出运行时错误,进一步影响页面渲染。

修复步骤

1. 添加匹配目标slug的文章数据

修改app/api/content/route.ts,加入slug为loremIpsum的文章条目:

import { NextResponse } from "next/server";

const posts = [
    {
        title:"nfcefce",
        slug:"ejcerc-334",
        content:"just and excer"
    },
    {
        title:"ej3e",
        slug:"ejcerc-334",
        content:"just a34j3oi"
    },
    {
        title:"opo909203",
        slug:"ejcerc-334",
        content:"just a23i939834"
    },
    // 新增匹配loremIpsum的文章
    {
        title:"Lorem Ipsum 示例文章",
        slug:"loremIpsum",
        content:"这是你要访问的文章内容"
    },
];

export async function GET() {
    return NextResponse.json(posts)
}

2. 处理文章不存在的边界情况

修改app/blog/[slug]/page.tsx,移除非空断言并添加404 fallback逻辑:

export const revalidate = 420

interface Post{
    title:string,
    content:string,
    slug:string,
}

interface Props{
    params:{slug:string}
}

export default async function page({params}:Props) {
    // 优化内部API调用路径,无需完整localhost地址
    const posts:Post[] = await fetch('/api/content', {
        next: { revalidate: revalidate } // 与页面缓存策略对齐
    }).then(res => res.json())
    
    const post = posts.find(post => post.slug === params.slug);

    // 文章不存在时返回404页面
    if (!post) {
        return (
            <div>
                <h1>404 - 文章不存在</h1>
            </div>
        )
    }

    return (
        <div>
            <h1>{post.title}</h1>
            <p>{post.content}</p>
        </div>
    )
}

3. 额外优化建议

  • 确保所有文章的slug唯一,避免重复导致匹配混乱。
  • Next.js中调用内部API时,使用相对路径即可,无需写完整域名,部署后仍能正常工作。
  • 利用next选项配置fetch的缓存策略,与页面的revalidate参数配合,实现灵活的内容更新机制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:08:31