【问题标题】:Invalid response from getStaticProps with Next.js来自带有 Next.js 的 getStaticProps 的无效响应
【发布时间】:2020-07-09 11:57:41
【问题描述】:

我正在尝试根据 Next.js 文档从本地服务器获取一些数据,但它响应以下错误:

FetchError:http://localhost:3000/agency/all 处的无效 json 响应正文原因:意外的令牌

我已经从 componentDidMount 和 Chrome 控制台尝试了相同的功能,并且两者都可以工作,但不知何故 Next 无法处理 getStaticProps 中的数据。当我尝试 axios 时也发生了类似的情况(它在 componentDidMount 上运行良好,但在 getStaticProps 上运行良好,尽管这一次它在此函数上响应 404,即使数据存在)。

我的代码如下:

import fetch from "node-fetch";


class Inmobiliarias extends React.Component {

    componentDidMount() {
        // This works
        async function getStuff() {
            const res = await fetch("http://localhost:3000/agency/all");
            const agencies = await res.json();
            console.log(agencies);
        }
        getStuff();
    }

    render() {
        return (
            // Component...
        );
    }
}


export async function getStaticProps() {
    // This doesn't work
    const res = await fetch("http://localhost:3000/agency/all");
    const agencies = await res.json();

    return { props: { agencies: agencies } };
}

export default Inmobiliarias;

我显然没有同时运行这两个函数:当我尝试 componentDidMount 时,我评论 getStaticProps,反之亦然。可能是什么问题?

谢谢!


编辑

我设法解决了这个问题:碰巧我的后端和 Node + Next 都运行在不同的 Docker 容器上,它们无法相互通信。解决方法是将fetch函数中的localhost地址改为后端容器的IP。答案来自这篇文章:ECONNREFUSED nodeJS with express inside docker container

【问题讨论】:

    标签: javascript node.js reactjs fetch next.js


    【解决方案1】:

    您应该在getInitialProps 中返回一个对象,如下所示:

    import fetch from "node-fetch";
    
    
    class Inmobiliarias extends React.Component {
        const { agencies } = this.props; 
    
        // use agencies
        console.log(agencies)
    
        render() {
            return (
                // Component...
            );
        }
    }
    
    
    export async function getStaticProps() {
        const agencies = 
          fetch("http://localhost:3000/agency/all")
            .then(res => res.json())
            .catch(error => console.log(erro))
    
        return { agencies };
    }
    
    export default Inmobiliarias;
    

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 2021-06-06
      • 2019-04-20
      • 2022-11-10
      • 2023-04-03
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2020-01-11
      相关资源
      最近更新 更多