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

Express API启动报EADDRINUSE错及注释路由仍生效问题求助

问题与解决方法

问题描述

正在学习全栈应用开发,跟着YouTube视频实操。第3个视频的配置一切正常,第4个视频配置express.static中间件后,离开一小时再运行新代码,终端报错EADDRINUSE: address already in use :::3000,同时访问localhost:3000时,已经注释掉的根路由仍返回'Hello, world!'。

报错信息

PS C:\Users\fred\To Do List> node ./src/index.js
node:events:368
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1330:16)
    at listenInCluster (node:net:1378:12)
    at Server.listen (node:net:1465:7)
    at Function.listen (C:\Users\lenaf\To Do List\node_modules\express\lib\application.js:635:24)
    at Object.<anonymous> (C:\Users\lenaf\To Do List\src\index.js:11:5)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/process/task_queues:83:21)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -4091,
  syscall: 'listen',
  address: '::',
  port: 3000
}

相关代码(index.js)

const express = require('express');

const api = express();
api.use(express.static(__dirname + '/public'));

api.listen(3000, () => {
    console.log('API up and running!')
});

/*
 Routes for the API
 api.get('/', (req, res) => {
     // console.log(req);
     res.send('Hello, world!');
 });
*/

解决方法

1. 解决端口占用问题

  • 杀掉占用3000端口的进程(Windows系统):
    打开命令提示符,依次运行以下命令:

    netstat -ano | findstr :3000
    

    找到输出结果中的PID数字,然后运行:

    taskkill /PID 你的PID数字 /F
    

    比如PID是1234,就执行taskkill /PID 1234 /F,强制关闭占用端口的进程。

  • 临时更换端口:
    修改代码中的监听端口,把api.listen(3000, ...)改成api.listen(3001, ...),之后访问localhost:3001即可。

  • 添加错误监听避免进程残留:
    修改代码,给服务器实例添加错误监听,方便快速定位问题:

    const server = api.listen(3000, () => {
        console.log('API up and running!')
    });
    
    server.on('error', (err) => {
        if (err.code === 'EADDRINUSE') {
            console.log('端口3000已被占用,请关闭对应进程或更换端口');
        }
    });
    

2. 解决注释路由仍返回内容的问题

  • 强制刷新浏览器缓存:
    按下Ctrl+Shift+R(Windows/Linux)或Cmd+Shift+R(Mac)强制刷新页面,清除浏览器缓存的旧响应。

  • 检查public目录下的index.html:
    express.static中间件默认会优先返回静态目录下的index.html文件,如果你的public文件夹里有这个文件,且内容是Hello, world!,就会显示它,和你注释的路由无关。检查并修改该文件即可。

  • 确认代码已保存:
    有时候编辑器未自动保存修改,导致运行的仍是旧代码。确认index.js确实保存了当前的修改后,再重新运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:55:17