【问题标题】:How to fix failing NextJS export - working fine locally but upon export it's failing, dismally :(如何修复失败的 NextJS 导出 - 在本地工作正常,但在导出时失败,令人沮丧:(
【发布时间】:2019-11-29 23:32:09
【问题描述】:

我正在 Next/React.JS 中开发视频/音乐流应用程序,从 Wordpress API/Backend/headless CMS 获取数据。它在 localhost 上运行良好(尽管目前它是真正的准系统功能) - 但是,当我尝试导出它以创建静态前端时,导出反复失败,并出现(可笑的常见且通常很简单)'无法读取未定义的属性' 错误。

在过去的 12 个小时里,我一直在严格调试并扫描 here/GH 等,在阳光下使用 then()/catch() await 等的所有组合,但我就是无法让它工作并且可以' t 为我的生活找出原因。我知道“标题”是未定义的,因为在导出时尚未获取数据,但是如何获取过去的“下一个导出”? 这是我的来自 single.js 的 getInitialProps - 问题似乎出在哪里,在控制台中没有其他相关错误 - 我将在下面尝试导出时发布终端消息。这是我在几十个版本之后回到的地方 - 这是漫长的一天,所以可能有一两个愚蠢的错误,但这个 在本地运行, 没有任何错误。

static async getInitialProps(context) {
    const slug = context.query.slug;
    let post = {};
    // Make request for posts.
    try {
      const response = await axios.get(
        `http://timeline-music-30.local/wp-json/wp/v2/posts?slug=${slug}`
      );

      post = response.data[0];
    } catch (err) {
      console.error(err);
    }

    return { post };

    // Return our only item in array from response to posts object in props.

    console.log("post:", post);
  }

我希望应用程序成功导出到静态站点,但它失败并显示以下终端消息:

copying "static build" directory
  launching 3 threads with concurrency of 10 per thread
[==--] 2/4 50% 118/s 0.0s TypeError: Cannot read property 'title' of undefined
    at _default.render (C:\Users\Terry\Documents\github\projects\timeline-music-3.0\nextjs\.next\server\static\YyI9s0TjENSVhc1SFZUcV\pages\single.js:158:35)

任何想法/帮助将不胜感激。

谢谢

特里

【问题讨论】:

    标签: javascript reactjs axios next.js


    【解决方案1】:

    首先,返回后不能console.log。

    第二。使用 isomorphic-fetch 和这种结构,我认为在你的情况下可以帮助:

    static async getInitialProps(context) {
        const slug = context.query.slug;
        // Make request for posts.
        const resPost = await fetch('http://timeline-music-30.local/wp-json/wp/v2/posts?slug=${slug}');
        const dataPost = await resPost.json();
    
        console.log("post:", dataPost.data[0]);
        return { post: dataPost.data[0] };
      }
    

    在组件中使用 {this.props.post}。 如果这没有帮助,请查看我的案例,它在本地和生产环境中工作:


    在我的类似情况下,我解决了同样的问题:

    我在http://computers.remolet.ru/ 网站上解决了这个问题。任务是根据域生成不同的内容,因此页面通过 fetch 从 API 请求内容。这是我解决这个问题的方法:

    添加到模块顶部:

    import getConfig from 'next/config';
    const nextConfig = getConfig();
    // npm i isomorphic-fetch need
    import 'isomorphic-fetch';
    

    在页面上抓取:

        static async getInitialProps ({ ctx }) {
            var host = '';
    
            if (nextConfig && nextConfig.publicRuntimeConfig && nextConfig.publicRuntimeConfig.HOST) {
                // server side
                host = nextConfig.publicRuntimeConfig.HOST;
            } else if (ctx && ctx.req && ctx.req.headers) {
                // front side
                host = 'http://' + ctx.req.headers.host;
            } else {
                // front side
                host = 'http://' + window.location.host;
            }
    
            const resPricelist = await fetch(host + '/api/pricelist');
            const dataPricelist = await resPricelist.json();
    
            const resNewPricelist = await fetch(host + '/api/newpricelist');
            const dataNewPricelist = await resNewPricelist.json();
    
            const resContent = await fetch(host + '/api/content');
            const dataContent = await resContent.json();
    
            return {
                pricelistData: dataPricelist,
                newPricelistData: dataNewPricelist,
                contentData: dataContent
            };
        }
    

    在组件中使用:

    <Header as="h1" align="center">
        {this.props.contentData.h1}
    </Header>
    

    在 next.config.js 中:

    module.exports = withCSS(withSass({
        cssModules: true,
        serverRuntimeConfig: {
            PORT: process.env.PORT, // eslint-disable-line no-process-env
            HOST: process.env.HOST, // eslint-disable-line no-process-env
            CONTENT: process.env.CONTENT // eslint-disable-line no-process-env
        },
        publicRuntimeConfig: {
            PORT: process.env.PORT, // eslint-disable-line no-process-env
            HOST: process.env.HOST, // eslint-disable-line no-process-env
            CONTENT: process.env.CONTENT // eslint-disable-line no-process-env
        }
    }));
    
    

    带环境的起始节点:

        "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1",
            "dev": "HOST='http://localhost:8000' PORT='8000' CONTENT='./db/computers.json' PRICELIST='./db/pricelist/computers.json' PRICELIST2='./db/pricelist/newComputers.json' node server.js",
            "build": "next build",
            "start": "next start"
        },
    

    这适用于本地主机和服务器。

    只需使用 isomorphic-fetch,如果你从绝对 url 获取,你所需要的只是构造:

    const resPricelist = await fetch(host + '/api/pricelist');
    const dataPricelist = await resPricelist.json();
    return {
        data: dataPricelist
    }
    

    这是大约 20 小时尝试和阅读 Next.js 论坛的结果。 希望能帮到你:)

    附:不要忘记您只能在页面组件上使用 getInitialProps ({ ctx }),而不能在子组件中使用!

    【讨论】:

    • 感谢您回复我!回到电脑前,我会尽快检查一下。
    • 是的,我认为控制台日志已被删除 - 这是早期迭代遗留下来的......就像我说的,这是漫长的一天......再次感谢。
    • 嗨 Oleg,所以 - 不幸的是,当使用“下一个导出”时,提取的内容仍然以未定义的形式返回 - 调试真的很头疼,因为我的屏幕上有提取 - 显示的内容。当我调试时,我可以看到数据 - 但是在导出时它总是说未定义 :( 我将在这一天剩下的时间里花时间 - 看看我是否能解决它,如果我不能解决它,我会分享我的GH repo,希望你(或某人)能告诉我哪里出错了。再次感谢
    • 好的!我将我的存储库公开了一段时间,测试我的代码,也许它会给你一些想法? github.com/Entegrato/RemoletBaseLanding
    • 我不得不关闭存储库,我收到了关于数据泄露的信件(我会忘记这个:)))。给我写信到 entegrato@gmail.com,我会给你访问权限。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2020-03-22
    相关资源
    最近更新 更多