【问题标题】:npm run build error , unable to run build command in next.jsnpm 运行构建错误,无法在 next.js 中运行构建命令
【发布时间】:2021-11-02 21:21:33
【问题描述】:

我正在尝试运行 npm run build 但我总是收到错误消息。即使所有页面都工作正常且没有错误。我使用 getServerSidePorps 添加了 api 调用代码。

错误:

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 调用

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,
    },
  };
};

【问题讨论】:

  • 请提供更多信息。这个错误什么时候出现?你的 package.josn npm 构建是什么样的,等等。
  • @wuno 在我运行 npm run build in next application 后 20 ,30 秒后我收到此错误。此消息显示我发送 axios 请求的 url
  • @wuno 我应该分享什么信息,请帮助我
  • 您是否在 pages 目录和 getStaticPaths 或 getStaticProps 内部进行 API 调用?
  • @wuno 是的,我已经添加了代码,请检查

标签: reactjs npm next.js


【解决方案1】:

问题 -

npm 构建失败并出现连接错误。

回答 -

您不应该 fetch()getServerSideProps() 中的 API 路由。

注意:您不应该使用 fetch() 来调用 API 路由 获取服务器端道具。而是直接导入里面使用的逻辑 你的 API 路由。您可能需要为此稍微重构您的代码 接近。

从外部 API 获取很好!

Check this link for more info -

这里的问题是您调用的是 API 路由而不是外部 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 2022-11-02
    • 2017-02-09
    • 1970-01-01
    • 2022-06-29
    • 2020-05-02
    • 2018-11-13
    • 2018-08-06
    相关资源
    最近更新 更多