【问题标题】:nginx server and node.js running faultynginx 服务器和 node.js 运行故障
【发布时间】:2014-07-20 04:19:17
【问题描述】:

我在本地机器上安装了 nginx 服务器和 node.js。我有以下 node.js 服务器:

//app.js
var fs = require("fs");
var express = require("express");
var app = express();

//app.use(express.static(__dirname + "/public"));

app.get("/", function(request, response){
    var content = fs.readFileSync("index.html");
    content = content.toString("utf8").replace("{{TEXT}}", "Home");
    response.setHeader("Content-Type", "text/html");
    response.send(content);
});

app.get("/hello/:text", function(request, response) {
var content = fs.readFileSync("index.html");
    content = content.toString("utf8").replace("{{TEXT}}", request.params.text);
    response.setHeader("Content-Type", "text/html");
    response.send(content);
}); 

app.listen(1337, "127.0.0.1");

如果我运行 nginx 服务器,localhost 我会得到 HTML 页面,但是“{{TEXT}}”没有被替换。如果我运行 localhost/hello/hi 我收到以下消息:500 内部服务器错误。

所以,在我的文件夹中,我有文件 app.js 和另一个名为 public 的文件夹。在 public 我有一个 index.html 文件。

我做错了什么?

另外,这是我的 nginx 配置:

upstream app_nodejs {
server 127.0.0.1:1337;
}

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

root /usr/share/nginx/html;
index index.html index.htm;

server_name localhost;

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    try_files $uri $uri/ /index.html;
    # Uncomment to enable naxsi on this location
    # include /etc/nginx/naxsi.rules
    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_nodejs;
    proxy_redirect off;

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

location /doc/ {
    alias /usr/share/doc/;
    autoindex on;
    allow 127.0.0.1;
    allow ::1;
    deny all;
}
}

【问题讨论】:

  • 更新:现在,如果我在本地主机上运行它,我会更改文本。但是,如果我在 localhost/hello/hi 运行,我会得到:Cannot GET /index.html。所有更改都已更新。
  • 嗨,丹。我们更喜欢这里的答案,而不是问题的附录。如果您将来想为另一个问题提供解决方案,我们鼓励您在此处自行回答(即使您接受另一个答案)。我刚刚为你移动了它。

标签: javascript node.js nginx


【解决方案1】:

Nginx 可以正常运行,但 node 可能没有。在大多数情况下,您不能在同一个端口上运行两台服务器,这似乎是导致问题的原因。 当文件不是静态文件时,找出正在运行的端口节点,并为它创建 nginx 管道。

【讨论】:

  • 我认为该节点无法正常运行。进行更改后,node.js 代码在“/”上运行。如果我在 localhost:1337 尝试一切正常。我猜是nginx和node之间的连接问题。而且,nginx 是 80,node 是 1337。
  • 谢谢你,你的回答“启发”了我找出问题所在:)
【解决方案2】:

代表 OP 发布。

解决了!

在 nginx 配置中,我为自定义路由添加了一个位置:

location /hello/ {
    location ~* {

proxy_pass http://app_nodejs;

    }
}

另外,对于其他没有定义的路由,我在app.js中抓到了:

app.get('*', function(req, res){
   res.send('Not found! Send the 404.html', 404);
});

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 2021-02-08
    相关资源
    最近更新 更多