简体   繁体   中英

Invalid response from getStaticProps with Next.js

I'm trying to fetch some data from a local server according to the Next.js docs, but it responds with the following error:

FetchError: invalid json response body at http://localhost:3000/agency/all reason: Unexpected token < in JSON at position 0

I've tried the same functions from componentDidMount and from the Chrome console and both work, but somehow Next is not able to process the data in getStaticProps. A similar situation has happened when I tried axios (it worked well on componentDidMount but not on getStaticProps, although this time it responded with 404 on this function even when the data existed).

My code is as follows:

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;

I'm obviously not running both functions at the same time: when I try componentDidMount, I comment getStaticProps, and viceversa. What could possibly be the problem?

Thanks!


EDIT

I managed to solve the problem: It happened that I had both the backend and Node + Next running on different Docker containers, and they couldn't communicate with each other. The solution was to change the localhost address in the fetch function to the IP of the backend container. The answer came from this post: ECONNREFUSED nodeJS with express inside docker container .

You should return an object in getInitialProps , like so:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM