Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js, getInitialProps do not work

when pages are rendered at server-site at first time or refresh the rendered page, getInitialProps do not work:

Home.getInitialProps = async ({store}) => {
    axios.post('/user').then(res => {
        var user = res.data;
        store.dispatch(setLoggingState(user));
    }, res => {
        console.log('4444');
    })
    return {};
}

In above code, server always print ‘4444’,and express did not receive the 'POST' request. tanks for your help

like image 877
travellingkite Avatar asked May 16 '26 08:05

travellingkite


1 Answers

  1. As @Fabian Schultz said, request url must be absolute in the getInitialProps, because a relative url cannot work on the server-side.
  2. The getInitialProps method should use async and await, like this:

    Home.getInitialProps = async ({store}) => {
      await axios.post('/user').then(res => {
        var user = res.data;
        store.dispatch(setLoggingState(user));
      }, res => {
        console.log('4444');
      });
      return {};
    }
    
like image 82
travellingkite Avatar answered May 17 '26 21:05

travellingkite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!