【问题标题】:Express multiple static route regex parsing表达多条静态路由正则表达式解析
【发布时间】:2017-04-25 13:18:45
【问题描述】:

我正在尝试使用 express 从两个目录提供静态文件。

我从两个目录提供服务的原因是由于目录 #1 中提供的文件在目录 #2 中具有匹配的目录名称之间的命名冲突

在目录 #1 中,它将只包含文件:

/path/to/dir1/foo                (where 'foo' is a file)

在目录 #2 中,它将包含包含文件的子目录:

/path/to/dir2/foo/bar            (where 'foo' is a dir && 'bar' is a file)

我的目标是能够执行以下命令:

wget "http://myserver:9006/foo"
wget "http://myserver:9006/foo/bar"

下面的 sn-p 将为我完成目录 #2 之前的所有工作:

"use strict";
const express = require('express');
const app     = express();

app.use('/',    express.static('/path/to/dir1/'))

const server = app.listen(9006, () => {
    let host = server.address().address;
    let port = server.address().port;

    console.log(`Example app listening at http://${host}:${port}`);
});

我正在尝试使用正则表达式添加第二个静态路由,以查看路由中是否有“/”,以便将其定向到目录 #2。我正在考虑这些方面的事情,但没有取得任何成功:

app.use('/[^/]*([/].*)?',    express.static('/path/to/dir2/'));

app.use('/.*/.*',    express.static('/path/to/dir2/'));

我将不胜感激。

提前致谢!

【问题讨论】:

    标签: node.js regex express


    【解决方案1】:

    根据the docs,你可以多次调用express.static,它会按照你指定目录的顺序搜索文件。

    文件夹结构:

    /
      static/
        s1/
          foo # Contents: s1/foo the file
        s2/
          foo/
            bar # Contents: s2/foo/bar the file.
    

    该应用程序是您的确切代码,除了两个静态行:

    const express = require('express')
    const app = express()
    
    app.use('/', express.static('static/s1'))
    app.use('/', express.static('static/s2'))
    
    const server = app.listen(9006, () => {
      let host = server.address().address
      let port = server.address().port
    
      console.log(`Example app listening at http://${host}:${port}`)
    })
    

    页面按预期工作

    $ curl localhost:9006/foo
    s1/foo the file
    
    $ curl localhost:9006/foo/bar
    s2/foo/bar the file.
    

    【讨论】:

    • 工作就像一个魅力!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2019-01-01
    • 2014-04-14
    • 2012-09-23
    相关资源
    最近更新 更多