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

Next.js从GraphQL API生成动态路径遇404及脚本加载问题求助

问题场景

我有一个项目列表页,访问单个项目详情页时持续出现404页面。尝试过Fetch与ApolloClient两种方式获取数据,问题均存在,有时还会触发「could not load scripts from page [].js」这类错误。以下是相关代码:

export async function getStaticProps({ params }) {
    const { projectId } = params

    const result = await fetch(
        `${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}/graphql`,
        {
            method: 'POST',
            headers: {
                // Authorization: `Bearer`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                query: `
                     query GetProject($path: String!) {
                        nodeArticles(where: {path: $path},limit: 1) {
                            nodes {
                                title
                                body {
                                    value:processed
                                }
                                image {
                                    url
                                }
                                path
                            }
                        }
                    }
                `,
                variables: {
                    path: projectId,
                },
            }),
        },
    );

    if (!result.ok) {
        console.error(result);
        return {};
    }

    const { data } = await result.json();

    const [ProjectData] = data.nodeArticles.nodes;

    return {
        props: { data: ProjectData || null },
    };

}
export async function getStaticPaths() {
    const result = await fetch(
        `${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}/graphql`,
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                query: `
                    {
                    nodeArticles(first: 100) {
                        nodes {
                                path
                            }
                        }
                    }
                `,
            }),
        },
    );

    if (!result.ok) {
        console.error(result);
        return {};
    }
    const { data } = await result.json();

    const projects = data.nodeArticles.nodes;

    const pagesPaths = projects.map(({ path }) => {
        return {
            params: { projectId: path },
        };
    });


    return {
        paths: pagesPaths || [],
        fallback: false,
    };
}

核心修复方案

1. 路径格式不匹配(404的主要诱因)

Drupal返回的path字段通常带前置斜杠(比如/projects/my-project),但Next.js动态路由[projectId].js需要的是无斜杠的路径片段。直接传入带斜杠的path会生成无效路由(比如/projects//projects/my-project),触发404。

修复代码:
在getStaticPaths中清理路径格式,同时在getStaticProps中补回Drupal需要的斜杠:

// getStaticPaths部分
const pagesPaths = projects.map(({ path }) => {
    // 去掉前置斜杠
    const cleanPath = path.replace(/^\//, '');
    // 若path是多级路径(如/projects/xxx),也可只取最后一段作为projectId:
    // const projectId = path.split('/').pop();
    return {
        params: { projectId: cleanPath },
    };
});

// getStaticProps的variables部分
variables: {
    path: `/${projectId}`, // 补回前置斜杠,匹配Drupal的path存储格式
},

2. 错误分支的正确返回

当前代码中fetch失败时,getStaticPaths直接返回{},会导致没有任何路径被预生成,所有详情页都会404。需要明确返回空路径数组:

// getStaticPaths的错误处理
if (!result.ok) {
    console.error(result);
    return {
        paths: [],
        fallback: false
    };
}

3. 空数据触发404

如果getStaticProps没拿到项目数据,当前会返回data: null,页面会渲染空内容但不触发404。可配置返回404:

const [ProjectData] = data.nodeArticles.nodes;

if (!ProjectData) {
    return {
        notFound: true, // 触发Next.js官方404页面
    };
}

return {
    props: { data: ProjectData },
};

4. 脚本加载错误的关联修复

「could not load scripts from page [].js」错误一般是路由路径异常导致Next.js无法正确解析资源路径,解决上述路径匹配问题后,该错误会自动消失。


额外验证点

  • 确认pages文件夹结构:若详情页是pages/projects/[projectId].js,则路由应为/projects/xxx,需和getStaticPaths生成的参数对应;
  • 直接调用Drupal GraphQL接口,确认nodeArticles.nodes.path的格式是否符合预期;
  • 临时设置fallback: true测试:若开启后能访问页面,说明getStaticPaths生成的路径未包含正确的项目路径。

内容的提问来源于stack exchange,提问作者Mohamed sadok yahyaoui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:45:45