0

i am trying to run npm run build but i always get an error .even though all the pages are working fine and no errors . I have added code for api calls using getServerSidePorps .

error:

Error: connect ECONNREFUSED 127.0.0.1:3000
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
  type: 'Error',
  config: {
    url: 'http://localhost:3000/api/admin/user/users/list',
    method: 'get',
    headers: {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/0.21.4'
    },
    transformRequest: [ null ],
    transformResponse: [ null ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    }
  },
  code: 'ECONNREFUSED'
}

API CALLS

export const getServerSideProps = async () => {
  const additionalData = {
    InitialSkip: 0,
    initialLimit: 3,
  };
  const response = await axios.post(
    "http://localhost:3000/api/admin/user/users/list",
    additionalData,
    {
      headers: {
        "Content-Type": "application/json",
      },
    }
  );

  return {
    props: {
      data: response.data,
    },
  };
};
juliomalves
  • 42,130
  • 20
  • 150
  • 146
node Dev
  • 69
  • 1
  • 7
  • Please provide more information. When does this error appear? What does your package.josn npm build look like, etc. – wuno Nov 02 '21 at 11:18
  • @wuno after i run npm run build in next application after 20 ,30 sec i get this error. this message shows url on which i send axios request – node Dev Nov 02 '21 at 11:19
  • @wuno what information should i share , kindly help me out – node Dev Nov 02 '21 at 11:20
  • Are you making an API call in the pages directory and inside of getStaticPaths or getStaticProps? – wuno Nov 02 '21 at 11:30
  • @wuno yes exactly , i have added code kindly check please – node Dev Nov 02 '21 at 11:33
  • Does this answer your question: [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/a/65760948/1870780)? Use the logic that's in your API route directly in `getServerSideProps`. – juliomalves Nov 02 '21 at 13:18

1 Answers1

0

Problem -

npm build fails with connection error.

Answer -

You should not fetch() to an API route in getServerSideProps().

Note: You should not use fetch() to call an API route in getServerSideProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach.

Fetching from an external API is fine!

Check this link for more info -

The issue here is that you are calling the API route and not an external API.

wuno
  • 9,547
  • 19
  • 96
  • 180