【问题标题】:Dynamic express.static() folder path动态 express.static() 文件夹路径
【发布时间】:2018-07-15 09:07:05
【问题描述】:

我有一个应用,使用 express.static 来访问一些用户信息,路由逻辑是这样的:

app.get('/principal',function(req,res,next){
    if(req.query.user=='admin'){
        next();
    }else{
        res.send("not allowed");
    }
});
app.use('/principal',express.static('/_site'));

但现在我需要它给所有用户,所以应该是这样的:

 var username = '';
 app.get('/principal',function(req,res,next){
        if(req.query.user){
            username = req.query.user;
            next();
        }else{
            res.send("not allowed");
        }
    });
    app.use('/principal',express.static(username+'/_site'));

我的每个用户名都有一个文件夹,我的 express.static() 一直读取用户名 var 为空。

【问题讨论】:

    标签: node.js express routes


    【解决方案1】:

    尝试从路由处理程序中提供静态文件,以使其对查询用户名动态:

    app.get('/principal',function(req,res,next){
        if(req.query.user){
    
            // serve static files for usename
            app.use('/principal', express.static(username +'/_site'));
    
            res.send("allowed");
        }else{
            res.send("not allowed");
        }
    });
    

    【讨论】:

    • 只显示“允许”页面,而不是我的 /_site 文件。如果我删除 res.send 它会永远加载
    • 是的,它会显示“允许”,但是如果您从 username +'/_site' 调用某个文件,它将呈现它,例如,假设您在某个用户名目录中有一个名为 style.css 的文件,让我们说leonardo,如果你去/principal/?user=leonardo,express会将./leonardo/_site设置为静态目录然后它会渲染allowed,现在如果你尝试调用路由/principal/style.cssexpress会渲染文件style.css位于./leonardo/_site
    • 工作。但我需要更改 'res.send("allowed");'到 res.sendfile(path, {root: '/_site'});.
    【解决方案2】:

    我认为express.static 无法做到这一点。但是,你可以,

    app.get('/principal', function(req, res){
        if(req.query.user){
            const username = req.query.user;
            const path = `${username}/boo.js`
            res.sendfile(path, {root: '/_site'});
        }else{
            res.send("not allowed");
        }
    });
    

    【讨论】:

    • 我用我的 index.html 文件做的,但它不加载我的 CSS/JS 文件,只加载 rae html。我做到了: const path = ${username}/index.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2020-06-28
    • 2017-08-31
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    相关资源
    最近更新 更多