我已经设置好 node .我的服务器上有js和Nginx.现在我想使用它,但在我开始之前,有两个问题:

  1. 他们应该如何合作?我该如何处理这些请求?
  2. node 有两个概念.js服务器,哪一个更好:

    a、 for each 需要的网站创建一个单独的HTTP服务器.然后在程序开始时加载所有JavaScript代码,这样代码就会被解释一次.

    b、 创建一个 node .处理所有 node 的js服务器.js请求.这将读取请求的文件并判断其内容.因此,每个请求都会解释文件,但服务器逻辑要简单得多.

我不清楚如何使用Node.没错.

推荐答案

Nginx充当前端服务器,在本例中,它将请求代理到 node .js服务器.因此,需要为 node 设置nginx配置文件.

这就是我在我的Ubuntu盒中所做的:

/etc/nginx/sites-available/处创建文件yourdomain.com:

vim /etc/nginx/sites-available/yourdomain.com

在里面你应该有这样的东西:

# the IP(s) on which your node server is running. I chose port 3000.
upstream app_yourdomain {
    server 127.0.0.1:3000;
    keepalive 8;
}

# the nginx server instance
server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com www.yourdomain.com;
    access_log /var/log/nginx/yourdomain.com.log;

    # pass the request to the node.js server with the correct headers
    # and much more can be added, see nginx config options
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://app_yourdomain/;
      proxy_redirect off;
    }
 }

If you want nginx (>= 1.3.13) to handle websocket requests as well, add the following lines in the location / section:

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

完成此设置后,必须启用上面的配置文件中定义的站点:

cd /etc/nginx/sites-enabled/ 
ln -s /etc/nginx/sites-available/yourdomain.com yourdomain.com

/var/www/yourdomain/app.js创建 node 服务器应用程序,并在localhost:3000运行

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

测试语法错误:

nginx -t

重新启动nginx:

sudo /etc/init.d/nginx restart

最后,启动 node 服务器:

cd /var/www/yourdomain/ && node app.js

现在你应该在你的域名上看到"Hello World".通用域名格式

关于启动 node 服务器的最后一个注意事项是:应该为 node 守护进程使用某种监视系统.有一个很棒的tutorial on node with upstart and monit.

Node.js相关问答推荐

postgresql层与应用层的序列化

MongoDB-如何验证Document字段以仅允许特定的文件扩展名?

如何在Mongoose中调用动态Collection ?

try 使用Express和连接池将数据插入MySQL数据库时出现拒绝访问错误

设置默认 node 版本

为什么 client.on("messageCreate") 的 TextChannel 中缺少 nsfw 属性?

使用 NPM 三个 mocha+typescript 进行测试

在 Node JS 中使用 url 链接而不是文件路径

为什么后端开发需要单独的服务器?

kubernetes 上的 nextjs 无法启动

如何从名字,中间名,姓氏中获取全名并在结果中搜索匹配?

使用中的端口代码:'EADDRINUSE',即使在 kill 命令之后

如何在 Nest.js 中使用查询参数?

使用 Node.js 在内存中缓冲整个文件

如何使用 Puppeteer 从输入中删除现有文本?

ISODate 未定义

如何可靠地散列 JavaScript 对象?

未在 Windows 8.1 上构建的 node 包 - 缺少 Microsoft.Cpp.Default.props

Nodejs将字符串转换为UTF-8

从 node.js 连接到 mongodb 时出现 ECONNREFUSED 错误