nodejs:显示不在公用文件夹中的图像

时间:2018-03-26 17:49:37

标签: javascript node.js express ejs

我想显示一个不在我的webroot的公共文件夹中的图像。 我的hirarchy:

Webroot
--core
----views
----public <- Here is where stylesheets and other images are
------index.ejs <- Here I want to display the file.jpg
--data
----userdata
------username <- this folder is named by the user
--------assignment <- this folder is named by the assignment
----------file.jpg

我不知道,我可以将其移动到公共文件夹中并通过robots.txt进行规则,但我想,也许有更好的解决方案。

1 个答案:

答案 0 :(得分:1)

您可以将data目录作为静态目录提供,就像您的公共目录一样 - Serving static files in Express。您可能希望在静态路由之前设置一些身份验证中间件,或者每个人都能够看到彼此的数据。

以下是一个可能的示例:

// User authentication middleware
app.use(function(req, res, next) {
    // Some implementation that determines the user that made the request.
    req.username = 'foo';
    next();
});

// Serve the public assets to all authenticated users
app.use(express.static('public'));

// Prevent users from accessing other users data
app.use('/data/userdata/{username}/*', function(req, res, next) {
    if (req.username === req.path.username) {
        next();
    } else {
        res.sendStatus(401); // Unauthorized
    }
});

// Serve the data assets to users that passed through the previous route
app.use('/data', express.static('data'));