我已经在一个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

其他回答

对于windows, 任务管理器肯定会显示正在运行的节点进程。 尝试终止进程,它将解决问题。

我也遇到了同样的问题。最好的解决方法是(对于windows):

进入任务管理器。 滚动并找到名为。 Node.js:服务器端JavaScript 结束这个特定的任务。

好了! 现在执行npm start,它将像以前一样工作!

只是想提一个已经给出的答案没有涵盖的问题。它与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

Try opening the localhost in your browser. Just type: localhost:3000 in the address bar. If the app opens-up, it means your previous npm run is still active. Now, you can just make changes to the code and see the effects if you are designing the same app, or if you wanna run another app, just tweak the code (in index.js of previously running app) a little-bit and (probably refresh the browser tab) to make it crash ;)..... Now go run npm run start again from your new app directory. Hope this helps! :)

or

你可以打开任务管理器(WINDOWS_KEY+X >任务管理器),你会看到“Node.js:服务器端JavaScript”行。选择它并结束任务....现在应该可以工作了!!

如果不是,将应用程序的.env文件更改为包含端口:3002并运行新应用程序。这将允许您在不同的端口上运行两个独立的应用程序。干杯! !

服务器或应用程序的listen()方法可以添加在两个位置。 中搜索listen()方法用于应用程序启动 这就是为什么它返回作为服务器启动端口XXXX和端口XXXX已经在使用消息并排出现