You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express连接RabbitMQ失败,请求时出现ECONNREFUSED错误求助

问题解决方案

问题1:访问localhost:3000显示Cannot GET /

原因

你的Express服务器仅配置了POST /sendLog路由,未定义根路径(/)的GET请求处理逻辑,直接访问localhost:3000时,Express找不到对应处理方法,返回404错误。

解决方法

方案1:添加根路径路由

在Server.js中补充以下代码:

app.get("/", (req, res) => {
  res.send("Express服务器运行正常,请使用POST /sendLog接口发送日志");
});

方案2:使用正确接口地址

直接通过Postman向localhost:3000/sendLog发送POST请求,而非根路径。

问题2:POST请求时程序崩溃,报错Error: connect ECONNREFUSED ::1:5672

原因

该错误表示Node.js程序无法连接RabbitMQ服务,常见诱因包括:

  1. RabbitMQ服务未正常启动或未监听5672端口
  2. localhost解析为IPv6地址(::1),但RabbitMQ未配置监听IPv6
  3. 代码缺乏错误处理,连接失败时未捕获异常导致程序崩溃

解决步骤

步骤1:确认RabbitMQ服务状态

运行命令检查RabbitMQ是否运行:

# macOS/Linux
rabbitmqctl status

# Windows(进入RabbitMQ安装目录的sbin文件夹执行)
rabbitmqctl.bat status

若服务未运行,启动RabbitMQ:

# macOS/Linux
rabbitmq-server

# Windows
rabbitmq-server.bat

步骤2:修改RabbitMQ连接URL为IPv4地址

将config.js中的amqp://localhost改为amqp://127.0.0.1,强制使用IPv4连接:

module.exports = {
  rabbitMQ: {
    url: "amqp://127.0.0.1",
    exchangeName: "logExchange",
  },
};

步骤3:添加错误处理避免程序崩溃

在Producer.js的方法中添加try/catch捕获异常,同时在Server.js路由中处理错误:

修改Producer.js:

async createChannel() {
  try {
    const connection = await amqp.connect(config.rabbitMQ.url);
    this.channel = await connection.createChannel();
  } catch (error) {
    console.error("创建RabbitMQ通道失败:", error);
    throw error;
  }
}

async publishMessage(routingKey, message) {
  try {
    if (!this.channel) {
      await this.createChannel();
    }

    const exchangeName = config.rabbitMQ.exchangeName;
    await this.channel.assertExchange(exchangeName, "direct");

    const logDetails = {
      logType: routingKey,
      message: message,
      dateTime: new Date(),
    };
    await this.channel.publish(
      exchangeName,
      routingKey,
      Buffer.from(JSON.stringify(logDetails))
    );

    console.log(`The new ${routingKey} log is sent to exchange ${exchangeName}`);
  } catch (error) {
    console.error("发送消息失败:", error);
    throw error;
  }
}

修改Server.js的路由:

app.post("/sendLog", async (req, res, next) => {
  try {
    await producer.publishMessage(req.body.logType, req.body.message);
    res.status(200).send("日志发送成功");
  } catch (error) {
    res.status(500).send("发送日志失败: " + error.message);
  }
});

步骤4:检查端口占用情况

确认5672端口未被其他程序占用:

# macOS/Linux
lsof -i :5672

# Windows
netstat -ano | findstr :5672

若端口被占用,停止占用程序或修改RabbitMQ监听端口(不推荐新手操作)。

内容的提问来源于stack exchange,提问作者CodingTiger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:25:17