node js express路由所有路径

时间:2013-08-20 18:29:38

标签: node.js express routes

我正在使用快递。我喜欢创建一个路由,将所有类型为“get”的请求导航到url前缀'/ app / static / * pagePath'到“/ assets / app / static / pagePath”。 我试图做以下,但是不起作用。

app.get('/app/static/*path', function (req, res) {
    res.sendfile('assets/app/static/' + req.params.path);
});

有什么想法吗?

4 个答案:

答案 0 :(得分:3)

只需使用带有前缀和一些短路逻辑的中间件:

app.use('/app/static', function (req, res, next) {
  if (req.method !== 'get') {
    next();
    return;
  }
  res.sendFile(__dirname + '/assets' + req.path);
});

(这是未经测试的,所以可能不会100%准备好,但你明白了)

实际上,再看一下你的问题,你确定只有给出正确的根目录才能使express.static中间件处理这个问题吗?

app.use('/app/static', express.static(__dirname + '/assets'));

答案 1 :(得分:2)

如果要包含子目录,可以使用正则表达式;此正则表达式将匹配/app/static/

下的任何目录/文件结构
app.get(/^\/app\/static\/(.*)/, function (req, res) {
    console.log('assets/app/static/' + req.params[0]);
    res.sendfile('assets/app/static/' + req.params[0]);
});

至于你关于多个静态目录的问题,是的,你可以。只需app.use两个;

app.use("/static", express.static(__dirname + "/assets"));
app.use("/static", express.static(__dirname + "/alternate_assets"));

该文件将从找到它的第一个目录提供(首先搜索/assets,然后搜索/alternate_assets),但为了减少混乱,您可能希望避免使用相同的文件名两个目录。

答案 2 :(得分:0)

过去没有其他答案对我有用,因为他们错过了两个小细节:

  • app.use调用定义静态目录应该是异步的(例如包装在函数中),或者他们会在websocket建立连接之前尝试执行(在我看来,这是一个问题)使用Connect - 构建在Express之上的框架;我应该能够在文件顶部开始编写我的代码。)

  • 这些定义需要在发送之前发送在该(异步)函数体中引用该URL的HTML文件。

像这样:

app.get('/', function (req, res) { 
  app.use('/static', express.static(__dirname + '/static'));
  res.sendfile(__dirname + '/index.html'); 
});

然后你可以将它们直接包含在HTML(或SVG等)中,如下所示:

<link rel="stylesheet" href="static/index.css">

<image x="0" y="0" xlink:href="static/picture.svg" />

•等。

答案 3 :(得分:0)

GET / app / static / foo / bar / buz ---&gt; req.path === / app / static / foo / bar / buz so:

app.get('/app/static/:path*', function (req, res) {
    res.sendfile('assets' + req.path);
});
相关问题