我正在测试一个应用程序(希望在heroku上运行,但在本地也有问题)。当它运行http.Server.listen()时,它给我一个EACCES错误-但它只发生在一些端口上。

我在本地运行:

joe@joebuntu:~$ node
> var h = require('http').createServer();
> h.listen(900);
Error: EACCES, Permission denied
    at Server._doListen (net.js:1062:5)
    at net.js:1033:14
    at Object.lookup (dns.js:132:45)
    at Server.listen (net.js:1027:20)
    at [object Context]:1:3
    at Interface.<anonymous> (repl.js:150:22)
    at Interface.emit (events.js:42:17)
    at Interface._onLine (readline.js:132:10)
    at Interface._line (readline.js:387:8)
    at Interface._ttyWrite (readline.js:564:14)

我没有在端口900(或我尝试过的其他20个端口中的任何一个)上运行任何东西,因此这应该可以工作。奇怪的是,它确实在某些端口上工作。例如,端口3000可以正常工作。

是什么导致了这种情况?

更新1:

我发现在我的本地计算机上,EACCES错误出现了,因为我必须以root身份运行node才能绑定到那些特定的端口。我不知道为什么会发生这种情况,但是使用sudo可以修复它。然而,这并不能解释我如何在Heroku上修复它。没有办法在Heroku上以root身份运行,所以我怎么能在端口80上监听?


当前回答

如果你使用的是Windows。您应该重新启动Windows NAT Driver服务。

以管理员身份打开命令提示符并运行

net stop winnat

then

net start winnat

就是这样。

这是因为我安装了Nord VPN,它是自动盯着窗口。

其他回答

对我有用的是,

解决方法1:我发现我的.env文件不正确。你不应该在变量之间使用','或';'分隔符。

解决方案2:如果它是一个react应用程序,确保你在客户端目录下,并且你没有试图在服务器目录下运行你的react应用程序(不是给你一个错误,而是解决问题)。

查看这个参考链接:

Give Safe User Permission To Use Port 80 Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/ Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024. A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands: sudo apt-get install libcap2-bin sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\`` Now, when you tell a Node application that you want it to run on port 80, it will not complain.

如果你使用的是Windows。您应该重新启动Windows NAT Driver服务。

以管理员身份打开命令提示符并运行

net stop winnat

then

net start winnat

就是这样。

这是因为我安装了Nord VPN,它是自动盯着窗口。

对我来说,这只是.env文件中的一个错误。我删除了每行末尾的逗号,问题就解决了。

之前:

HOST=127.0.0.1,

后:

HOST=127.0.0.1

2023

Linux(任何发行版)

您可以使用CAP_NET_BIND_SERVICE,这是Linux的核心功能之一:

CAP_NET_BIND_SERVICE 将套接字绑定到Internet域特权端口(端口号小于1024)。

您可以给任何二进制文件一个永久权限来访问< 1024个端口。

以Node.js为例,它看起来像:

sudo setcap CAP_NET_BIND_SERVICE=+eip $(which node)

如果您愿意,您也可以稍后通过运行以下命令删除此权限:

setcap -r $(which node)