ExpressJs服务多个静态文件夹不起作用

use*_*083 3 node.js express

我想构建我的公用文件夹,如下所示:

 - public
     -  frontend
     -  backend
     -  assets   # to serve common css, and js static files for backend/frontend
Run Code Online (Sandbox Code Playgroud)

如果请求以/ admin为前缀,那么我想提供后端文件夹,否则后端文件夹这是我试过的

app.use(function(req, res, next) {
    if (req.url.match('^\/admin')) {
        express.static(__dirname + '/public/admin')(req, res, next);
    } else {
        express.static(__dirname + '/public/frontend')(req, res, next);
    }
});

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

app.get('*', function(req, res, next) {
    if (req.url.match('^\/admin')) {
        res.sendFile(__dirname + '/public/admin/app/views/index.html');
    } else {
        res.sendFile(__dirname + '/public/frontend/app/views/index.html');
    }
});
Run Code Online (Sandbox Code Playgroud)

但是我无法从assets文件夹中获取静态文件,而是继续给我index.html.什么是使其有效的正确方法?多谢

小智 5

如果我正确地理解了你的问题,我认为这样的事情会更好.

app.use('/admin', express.static('public/backend'));
app.use('/', express.static('public/frontend'));
Run Code Online (Sandbox Code Playgroud)