我已经在一个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来检查哪个进程正在使用该端口,但是没有使用该端口。我也尝试重新启动我的笔记本电脑,但我仍然得到同样的错误。


当前回答

这是一个老问题,但似乎没有一个回复者真正读过它。我也遇到过同样的问题,问题是Windows有时会保留端口块并阻止你使用它们。该端口不会通过netstat或任何其他工具显示。你可以在这里阅读:

从本质上讲,你可以告诉Windows离开你的端口:

netsh int ipv4 add excludedportrange tcp startport=3000 numberofports=1 store=persistent

其他回答

确保在hosts文件中配置了localhost

127.0.0.1       localhost

https://github.com/facebook/create-react-app/issues/2843

它可能是在后台运行的管理进程,netstat没有显示这一点。 使用任务列表| grep节点找到这个管理进程的PID,然后杀死PID

来自谷歌的High Sierra解决方案。

macos的网络设置发生了变化,一些应用程序(包括ping)无法解析localhost。

编辑/etc/hosts似乎是一个解决方案:

命令:sudo nano /etc/hosts/ 内容127.0.0.1 localhost

或者简单地说(如果你确定/etc/hosts是空的) 必须回显“127.0.0.1 localhost”> /etc/hosts

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

npx kill-port 3000


杀死多个端口。

npx kill-port 3000 8080 4200

在linux中很简单

打开终端 进程中的空闲端口 -> kill $(lsof -t -i:$port)