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.
That makes sense. You need to add the full path. Since getInitialProps is executed on the server and on the client.
On the client relative paths should work, but not on the server (in the node.js context).
If you still want to use relative paths check out axios basePath setting: https://github.com/axios/axios#request-config
...
baseURL: 'http://abc.herokuapp.com/api/',
...
I replaced const res = await Axios.get("/api/recent/1"); to
const res = await Axios.get("http://localhost:3000/api/recent/1");
Its working fine now. But could you tell why don't I have to do this when I do Api call in componentDidMount. Its works fine in componentDidMount without doing the above stuff.
componentDidMount is only called on the client.
componentDidMount()is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. ...
https://reactjs.org/docs/react-component.html#componentdidmount
To fully explain:
Node.js is not aware of any base url. Your browser is. So on the server side you have to provide the full path, on the client side when using relative links they're relative to the base url, eg https://example.com
Most helpful comment
To fully explain:
Node.js is not aware of any base url. Your browser is. So on the server side you have to provide the full path, on the client side when using relative links they're relative to the base url, eg
https://example.com