将请求 localhost:3000/api/product 代理到 http://localhost:5000/ 时出错

Error occurred while proxying request localhost:3000/api/product to http://localhost:5000/

我们正在尝试使用 Typescript、express 和 nextjs 创建一个简单的电子商务应用程序。

当我们向它发出请求时,它会抛出以下错误。

[HPM] Error occurred while proxying request localhost:3000/api/product to http://localhost:5000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)

我的朋友正在使用 Windows,代码可以在他的 PC 上运行,但不能在我的 Ubuntu 桌面上运行。

我试过如下关闭端口。它也关闭了端口,但这没有帮助。

$ sudo lsof -t -i:5000
6033
$sudo kill -9 6033

$sudo lsof -t -i:3000
6101
$sudo kill -9 6101

代理服务器正在侦听 server.js 文件为:

const express = require('express');
const next = require('next');
const { createProxyMiddleware } = require('http-proxy-middleware');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();
    // apply proxy in dev mode
    if (dev) {
      server.use(
        '/api',
        createProxyMiddleware({
          target: 'http://localhost:5000',
          changeOrigin: true,
        })
      );
    }

    server.all('*', (req, res) => {
      return handle(req, res);
    });

    server.listen(3000, (err) => {
      if (err) throw err;
      console.log('> Ready on http://localhost:5000');
    });
  })
  .catch((err) => {
    console.log('Error', err);
  });

找到解决方案。

我忽略了 .gitignore

中的 node_moduleupload 文件夹

克隆后忘了添加文件夹。所以,它显示代理错误。

添加上传后文件夹错误已解决。