【问题标题】:trouble getting a file from node.js using nginx reverse proxy使用 nginx 反向代理从 node.js 获取文件时遇到问题
【发布时间】:2016-11-24 00:14:10
【问题描述】:

我已经设置了一个 nginx 反向代理到节点,基本上使用this 设置复制如下:

upstream nodejs {
    server localhost:3000;
}

server {
    listen 8080;
    server_name localhost;
    root ~/workspace/test/app;

    location / {
        try_files $uri $uri/ @nodejs;
    }

    location @nodejs {
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_pass http://nodejs;
        proxy_set_header Host $host ; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

现在,我所有的 AJAX POST 请求都可以通过此设置很好地传输到节点,但是之后我正在轮询文件,当我向节点服务器发出客户端 AJAX GET 请求(通过这个 nginx 代理)时,我找不到这些文件。

例如,对于像 .get('Users/myfile.txt') 这样的客户端 javascript 请求,浏览器会在 localhost:8080 上查找文件,但不会找到它,因为它实际上已写入 localhost:3000

http://localhost:8080/Users/myfile.txt // what the browser searches for
http://localhost:3000/Users/myfile.txt // where the file really is

如何设置代理以导航到此文件?

【问题讨论】:

  • Node.js 好像是路由到 8080 的,能显示一下相关配置吗?
  • 我正在使用节点和快递。我能想到的唯一配置文件是我发布的 nginx。一种情况是我有app.post('/data') 来处理节点服务器代码中的数据,但没有app.get()。该文件是由一个单独的引擎编写的。我是否需要在节点中明确设置app.get() 才能识别代理?还是 nginx.conf 中的罪魁祸首?
  • 对不起,我看错了。它路由到 8080,因为那是您的 NGINX 配置正在监听的内容。无论如何,如果在try_files 指令处失败,NGINX 会将其代理到端口 3000,因此它仍然应该找到该文件。您是否在日志文件中收到 404?
  • 是的 404 在日志文件中。我正在为 HEAD 投票,我得到 .... "HEAD /Users/myfile.txt HTTP/1.1" 404 0 "http://localhost:8080/" ...

标签: ajax node.js nginx proxy


【解决方案1】:

好的,我搞定了。上面发布的nginx.conf 文件中的设置很好。这个问题从来都不是 nginx 的问题。问题出在节点服务器上的我的index.js 文件中。

当我让 nginx 为所有静态文件提供服务时,我从 index.js 中注释掉了以下行

app.use(express.static('Users')); // please don't comment this out thank you

我花了一些时间来解决我的问题,因为我非常专注于理解 nginx。我当时的想法是,如果 nginx 提供静态文件,为什么我需要 express 来提供它们?但是,如果没有这一行,express 显然不会提供任何文件。

现在通过正确的快速服务静态文件,nginx 处理来自 web 应用程序的所有静态文件,节点处理来自后端的所有文件,一切都很好。

感谢Keenan Lawrence 的指导和AR7 的配置!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2021-06-11
    • 2020-05-20
    • 2019-04-17
    • 2012-12-11
    • 1970-01-01
    相关资源
    最近更新 更多