网站搜索

node.js - Next JS - 如何修复错误:connect ECONNREFUSED 127.0.0.1:3003 在 TCPConnectWrap.afterConnect [作为 oncomplete]


我刚接触 Next JS。我无法在本地构建我的应用程序。当我输入 npm run build 命令时,出现以下错误:

...
_currentUrl: 'http://localhost:3003/data/menus.json',
    [Symbol(kCapture)]: false
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON]
}
Error: connect ECONNREFUSED 127.0.0.1:3003
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1148:16) {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3003,
  config: {
    url: 'http://localhost:3003/data/menus.json',
    method: 'get',
    headers: {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/0.21.4'
    },
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
...

而在日志的最后

...
info  - Generating static pages (771/771)

> Build error occurred
Error: Export encountered errors on following paths:
        /ar
        /ar/classic
        /ar/minimal
        /ar/standard
        /ar/vintage
        /de
        /de/classic
        /de/minimal
        /de/standard
        /de/vintage
        /en
        /en/classic
        /en/minimal
        /en/standard
        /en/vintage
        /es
        /es/classic
        /es/minimal
        /es/standard
        /es/vintage
        /fr
        /fr/classic
        /fr/minimal
        /fr/standard
        /fr/vintage
        /he
        /he/classic
        /he/minimal
        /he/standard
        /he/vintage
        /zh
        /zh/classic
        /zh/minimal
        /zh/standard
        /zh/vintage
    at C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\export\index.js:487:19
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async Span.traceAsyncFn (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\telemetry\trace\trace.js:60:20)
    at async C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\build\index.js:833:17
    at async Span.traceAsyncFn (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\telemetry\trace\trace.js:60:20)
    at async C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\build\index.js:707:13
    at async Span.traceAsyncFn (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\telemetry\trace\trace.js:60:20)
    at async Object.build [as default] (C:\Users\PC\OneDrive\Documents\lab\samara\laravel\node_modules\next\dist\build\index.js:77:25)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed.
Exit code: 1
Command: C:\Program Files\nodejs\node.exe
Arguments: C:\Users\PC\.node\corepack\yarn\1.22.15\lib\cli.js build
Directory: C:\Users\PC\OneDrive\Documents\lab\samara\laravel\shop
Output:

info Visit https://yarnpkg.com/en/docs/cli/workspace for documentation about this command.
error Command failed with exit code 1.

npm run dev 命令运行没有任何问题。所以在本地应用程序没有问题。但当我发布到生产环境,想要构建时,我遇到了以上这些错误。

这是我的 server.js 文件:

// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const hostname = 'localhost';
const port = 3003;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer(async (req, res) => {
    try {
      // Be sure to pass `true` as the second argument to `url.parse`.
      // This tells it to parse the query portion of the URL.
      const parsedUrl = parse(req.url, true);
      const { pathname, query } = parsedUrl;

      if (pathname === '/a') {
        await app.render(req, res, '/a', query);
      } else if (pathname === '/b') {
        await app.render(req, res, '/b', query);
      } else {
        await handle(req, res, parsedUrl);
      }
    } catch (err) {
      console.error('Error occurred handling', req.url, err);
      res.statusCode = 500;
      res.end('internal server error');
    }
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://${hostname}:${port}`);
  });
});

以及我的 package.json 文件

{
  "name": "@samara/shop",
  "version": "1.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev -p 3003",
    "build": "next build",
    "start": "NODE_ENV=production node server.js"

如果你需要检查另一个文件,请告诉我。

答案#1

我不知道这是否是最好的方法,但在我的情况下,我先运行 npm run dev,然后运行 npm run build,错误就不会再发生,然后停止开发并运行 npm run start

如果你在 getStaticProps 函数中调用 API http://localhost:3003/data/menus.json,你也可以在调用中添加 try catch,如果需要重新验证,可以在 catch 中将重新验证时间设置为 1 秒

答案#2

我通过 node server.js 手动运行了服务器,然后运行了 npm run build,它就成功了。这可能是因为在我构建文件时服务器没有运行,而在其中一个 useEffect 中我使用了 API,由于服务器没有启动,所以显示了错误。