簡體   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