我已经在一个node.js项目上工作了几个星期,它一直工作得很好。通常,我使用npm start来运行我的应用程序,并在localhost上的浏览器中查看它,端口3000。

今天,我在使用npm start时开始得到以下错误:

Server started on port 3000                                                                                                                                                                                         
Port 3000 is already in use 

我已经检查了资源监视器,我没有在端口3000上运行其他进程。我为什么会得到这个错误消息?

在我的app.js中,我有以下代码来设置端口…这是错误的吗?它以前工作得很好,所以我不确定我做错了什么。

// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function() {
    console.log('Server started on port '+app.get('port'));
});

谢谢你的帮助!


编辑:

我已经尝试运行netstat和TCPView来检查哪个进程正在使用该端口,但是没有使用该端口。我也尝试重新启动我的笔记本电脑,但我仍然得到同样的错误。


当前回答

在运行nodemon之前,请先启动mongod。您永远不会得到这个错误。

其他回答

打开任务管理器(按Ctrl+Alt+Del 选择“流程选项卡” 搜索“Node.js:服务器端JavaScript” 选择它并单击“结束任务”按钮

打开命令提示符,首先运行以下命令:

netstat -ano | findstr :7001

然后执行以下命令:

taskkill /PID 2820 /F

你可以使用kill-port。首先,关闭现有端口,然后创建服务器并监听。

const kill = require('kill-port')

kill(port, 'tcp')
    .then((d) => {
        /**
     * Create HTTP server.
     */
        server = http.createServer(app);

        server.listen(port, () => {
            console.log(`api running on port:${port}`);
        });
    })
    .catch((e) => {
        console.error(e);
    }) 

也许你可以拿这个作参考。这个命令行可以终止在给定端口上运行的进程。

npx kill-port 3000


杀死多个端口。

npx kill-port 3000 8080 4200

只是想提一个已经给出的答案没有涵盖的问题。它与Hyper-V(和Docker)有关“窃取”端口:

摘自Docker问题(链接如下):

禁用hyper-v(这需要重新启动几次)

dism.exe /Online /Disable-Feature:Microsoft-Hyper-V

当您完成所有必需的重新启动时,保留您想要的端口,这样hyper-v就不会再保留它

netsh int ipv4 add excludedportrange protocol=tcp startport=3000 numberofports=1

重新启用hyper-V(这需要重新启动几次)

dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All

https://github.com/docker/for-win/issues/3171#issuecomment-459205576