繁体   English   中英

nginx服务器和node.js运行错误

[英]nginx server and node.js running faulty

我在本地计算机上安装了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服务器,则本地主机会显示HTML页面,但不会替换“ {{TEXT}}”,如果运行localhost / hello / hi,则会显示以下消息:500 Internal Server Error。

因此,在我的文件夹中有文件app.js和另一个名为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;
}
}

Nginx可以正确运行,但是节点可能不是。 在大多数情况下,您不能在同一端口上运行两台服务器,这似乎是造成此问题的原因。 当文件不是静态的时,找出正在哪个端口节点上运行,并使其通过nginx传递。

代表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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM