javascript - Node : display an image not in public folder

标签 javascript node.js express ejs

我想显示不在我的网站根目录的公共(public)文件夹中的图像。 我的等级制度:

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

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

最佳答案

您可以将 data 目录作为静态目录,就像您的公共(public)目录 -- 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'));

关于javascript - Node : display an image not in public folder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49497594/

相关文章:

javascript - 确保用户无法修改 url 中的 id

javascript - 如何捕获信息框关闭事件(Google Maps API V3)

javascript - 如何使用 AngularJS 根据选择更改更新对象数组

javascript - 尝试使用 Javascript 动态更改 CSS 失败。为什么?

javascript - 处理 javascript db.transaction 回调

node.js - 如何在 Bookshelf js 中使用 groupBy?

node.js - node api 上的 mocha chai 测试总是收到 404 状态

javascript - 用js和foreach为元素腾出一段时间

javascript - Angular Universal 在 POST 请求中使用我服务器的 IP 地址

node.js - 如何在 Express/node.js 应用程序中使用 mailgun/mailchimp/etc 发送电子邮件