在 NodeJS 中,您可以使用预先存在的东西,例如 express,或者基本上滚动您自己的网络服务器,尽管听起来令人生畏,但实际上在 nodejs 中很简单......
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(3000);
如果您想保持服务在您的服务器上运行,Forever 和 PM2 是最好的起点。 Forever 比 PM2 存在的时间更长,但我相信 PM2 比 Forever 功能更丰富(forever 使用起来稍微简单一些)。
关于 apache 或 nginx,您可以使用它们将请求转发到您的节点进程。 http 默认运行在端口 80 上,但是端口 80 将已被您的 apache 进程使用。我建议在另一个端口(例如 3000)上运行您的 nodejs 应用程序,并使用您现有的 Web 服务器(apache、ligtthpd、nginx 等)作为反向代理,我在下面提供了一个示例设置。
阿帕奇
<VirtualHost example.com:*>
ProxyPreserveHost On
ProxyPass /api http://localhost:3000/
ProxyPassReverse /api http://localhost:3000/
ServerName localhost
</VirtualHost>
Lighttpd
$HTTP["host"] == "example.com" {
server.document-root = "/var/www/example.com"
$HTTP["url"] =~ "(^\/api\/)" {
proxy.server = (
"" => (
(
"host" => "127.0.0.1",
"port" => "3000"
)
)
)
}
}
nginx
http {
...
server {
listen 80;
server_name example.com;
...
location /api {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
rewrite ^/api/?(.*) /$1 break;
proxy_pass http://localhost:3000;
}
...
}
}
在上述示例中,对http://example.com/api 的任何请求都将被重定向到在端口 3000 上运行的节点进程。
这里的想法是,您使用网络服务器来提供静态文件(例如 css),并使用节点进程来提供应用程序。