javascript - 如何修复失败的 NextJS 导出 - 在本地工作正常,但导出时失败,令人沮丧 :(

标签 javascript reactjs axios next.js

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

我花了过去 12 个小时严格调试并扫描here/GH等,在阳光下使用then()/catch()await等的所有组合,但我就是无法让它工作并且不能'我一生都想弄清楚为什么。我知道“标题”未定义,因为导出时尚未获取数据,但如何获取过去的“下一次导出”? 这是我来自 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)

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

谢谢

特里

最佳答案

首先,返回后无法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 }) ,而不能在子组件中使用!

关于javascript - 如何修复失败的 NextJS 导出 - 在本地工作正常,但导出时失败,令人沮丧 :(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57138416/

相关文章:

javascript - 跨源资源错误 : No 'Access-Control-Allow-Origin' header is present on the requested resource

json - vuejs : the correct path of local json file for axios get request

file-upload - 向Redmine API发送POST请求时如何修复 '422 Unprocessable Entity'?

javascript - d3.js Sankey Link Transition 未就地转换(提供 jsbin)

javascript - 验证用户名-最佳正则表达式

javascript - 是否有适用于 Notepad++ 的 Google Closure Compiler 插件

javascript - 如何测试 axios 包装器

c# - 检查 Selenium 测试中的 Javascript 错误

reactjs - 如何从 Intellij 运行/执行/调试 react/redux 应用程序

javascript - 如何将表单中的变量传递给 React.js 中的 onclick 函数?