更改 expressjs 应用程序的根文件夹

Change root folder of expressjs app

我正在尝试在 nodejs 中设置 twilio 客户端快速启动应用程序。我使用 nginx 作为反向代理,以便对 http://example.com/calls 发出的请求,nginx 将其路由到 localhost:3000,在那里我有 twilio nodejs quickstart 运行。问题是 expressjs 期望像我调用没有子目录的 http://example.com 一样提供文件。

我知道我可以使用 app.get,但我不确定这个特定应用程序的配置方式。现在它有:

const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');

const router = require('./src/router');

// Create Express webapp
const app = express();
app.use(express.static(path.join(__dirname, 'public')));// <-Pretty sure I'm supposed to change something here
app.use(bodyParser.urlencoded({extended: false}));

在index.js节点运行在

/var/www/example.com/calls/index.js

我认为应该提供的静态内容位于

/var/www/example.com/calls/public/index.html

如何更改此设置以使 express 找到内容?

Nodejs 确实收到了请求。错误是 Cannot GET /calls/ 并且存在 header X-Powered-By 并设置为 Express

编辑:

我希望按照说明进行操作 here,但我的 at&t 防火墙不允许我进行更改。因为我已经打开了端口 80 和 443,所以我决定下一个最好的选择是将应用程序代理到我的系统上已有 运行 的域的子文件夹。到目前为止提供的两种解决方案都允许提供 /public 文件夹内的 index.html 文件,但是 nginx 无法提供 js 文件或位于同一文件夹中的 css 文件文件夹。

app.use('/calls',express.static(path.join(__dirname, '/public')));

目前正在 https://example.com/calls, which is great. What stinks is the nginx somehow isn't passing the requests for https://example.com/calls/site.css 上为 nodejs 提供 index.html 文件。

如果我添加行

rewrite ^/cawls(.*)$  break;

然后什么也找不到。

这是 nginx 调用。

    location ~/calls(.*)$ {
#        rewrite ^/calls(.*)$  break;
        proxy_pass   http://127.0.0.1:3000;
    }

Here and 是以前与此问题相关的问题,但似乎没有人能回答。

我还没有看到 express.static 用于 HTML。从路线提供服务怎么样?

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'public/index.html'));
})

这里是 Twilio 开发人员布道者。

这里的问题是 express 对您的 /calls 路线一无所知。它期望在其应用程序根目录下提供内容。您可以通过将 /calls 路由附加到您的静态中间件来在应用程序中修复此问题,如下所示:

app.use('/calls', express.static(path.join(__dirname, 'public')));

但这意味着您的 express 应用程序知道您正在使用 nginx 进行反向代理的其余应用程序。相反,我建议您将 nginx 配置更新为代理传递,但去除 express 应用程序的 /calls 路由。

我猜你有一些看起来有点像这样的 nginx 配置:

location /calls {
    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://localhost:3000;
    proxy_redirect off;
}

如果您向此块添加一行,它应该删除 /calls 路由,以便您的 Express 应用程序受益。

rewrite ^/calls(/.*)$  break;

如果这些事情有帮助,请告诉我!