端口100不在localhost中的node.js中运行

我使用下面的代码在node.js中创build了一个http服务器,并试图在端口100上运行它:

var http = require("http"); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end("Howdy"); }).listen(100); console.log("server running on port 100"); 

有了这个,服务器不会启动,我在Linux控制台上收到以下错误消息:

 events.js:72 throw er; // Unhandled 'error' event ^ Error: listen EACCES at errnoException (net.js:901:11) at Server._listen2 (net.js:1020:19) at listen (net.js:1061:10) at Server.listen (net.js:1135:5) at Object.<anonymous> (/home/badhai/Desktop/mainn.js:6:4) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) 

但是,如果我解除端口100上的sails.js应用程序,它将在端口100上成功运行。但是,上述代码在端口8081上成功运行。我想知道是否需要在服务器创build方法或其他位置进行任何更改它可以使端口100上成功运行?

错误信息的EACCES部分是这里的关键 – 这意味着您无法访问该端口。 端口<1024是系统保留的。 最好使用1024-65535范围内的端口

大多数现代操作系统将绑定到保留端口(小于1024)限制为以root身份(或等效)运行的进程。

如果你绝对必须绑定到100端口,谷歌search会给你一堆方法来做到这一点:

https://gist.github.com/firstdoit/6389682

最好使用1024以上的端口。我使用3000以上的端口。但是如果你真的想在100端口上启动它,并且你明白你在做什么,那么安装setcap ,只允许绑定端口<1024。

 > sudo apt-get install setcap > sudo setcap 'cap_net_bind_service=+ep' /usr/local/bin/node 

NodeJS也可以安装在其他目录中,所以最好检查它的位置,并用你的path调用setcap命令。

 > which node /usr/local/bin/node