node.js - 如何使用 Express 和 NGINX 设置路由?

标签 node.js express nginx server digital-ocean

我正在尝试使用 NGINX 配置 Express 服务器作为反向代理。 NGINX 提供静态文件,Express 提供动态内容。

问题:正常的根链接有效(website.com),但是当我导航到(website.com/api)时,我从 NGINX 收到 404


这是我的 server.js :

var express = require("express");
var app = express();
var server = app.listen(process.env.PORT || 5000);

console.log("Server Running");

app.get("/",function(req,res){res.send("HOME PAGE")});

app.get("/api", function(req, res) {
    res.send('API PAGE');
});

这是我的 NGINX 配置文件:

server {
    listen 80 default_server;
    listen [::]:80 default_server;


    server_name website.com www.website.com;

    location ~ ^/(assets/|images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) {
    root /home/foobar/public; #this is where my static files reside
    access_log off;
    expires 24h;
    }

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect off;
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

        try_files $uri $uri/ =404;
    }
}

最佳答案

尝试删除这一行:

try_files $uri $uri/ =404;

使用此指令,nginx 会尝试提供静态文件(或目录),如果没有这样的文件,则返回 404

关于node.js - 如何使用 Express 和 NGINX 设置路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44668559/

相关文章:

ruby-on-rails - Capistrano-Rails 错误 : Unable to access log file + unicorn: Permission denied

node.js - Docusaurus 2 中的自定义搜索栏

node.js - Nodejs Express hbs : css MIMETYPE turns into text/html

ubuntu - nginx 每天崩溃,error.log 什么也没显示

node.js - 如何在 Jade 模板中预填充编辑页面(Node + Express + Jade)

ajax - 在 AJAX 调用(使用 ExpressJS)之后,在 EJS 模板中循环遍历数组的正确方法是什么?

jquery - nginx comet 使用 jquery 进行长轮询

javascript - 在 pug (jade) 和 Node.js 中迭代两个数组

javascript - 来自 URL 的 Nodejs 查询不起作用

javascript - 在 Node javascript中使用selenium-webdriver执行 "commands"