1

When I use internal API route in getInitialProps I get this error.

Error: read ECONNRESET
    at _errnoException (util.js:1003:13)
    at TCP.onread (net.js:620:25)

static async getInitialProps({ reduxStore }) {
    const res = await Axios.get("/api/recent/1");
    await reduxStore.dispatch({ type: LIST, payload: res.data });
    return { }
}

But If I use external API server, it works fine.

static async getInitialProps({ reduxStore }) {
    const res = await Axios.get("http://abc.herokuapp.com/api/recent/1");
    await reduxStore.dispatch({ type: LIST, payload: res.data });
    return { }
}

If I call API in componentDidMount, it works fine in both cases, but in getinitialProps I couldn't handle internal API which are on my Express server.

Please help! Is there a problem in my code? I am searching from past couple of hours but couldn't solve it.

chunkydonuts21
  • 79
  • 1
  • 10

1 Answers1

0

You can extract the baseUrl from the request.

async getInitialProps({ req }) {
    const protocol = req.headers['x-forwarded-proto'] || 'http'
    const baseUrl = req ? `${protocol}://${req.headers.host}` : ''

    const res = await fetch(baseUrl + '/api/recent/1')
    ...
}
bubbleChaser
  • 755
  • 1
  • 8
  • 21