【问题标题】:Node.js - How to hide html pages?Node.js - 如何隐藏 html 页面?
【发布时间】:2020-05-06 22:01:58
【问题描述】:

我的 html 页面不应该被未登录的用户看到。我使用下面的命令,我的 html 页面被公开了。

app.use(express.static('public'));

例如,我不希望未登录的用户看到此页面。

http://localhost:3000/admin.html

注意:我所说的不是 cookie。当你在工具栏中输入html页面的地址时,如果没有登录,应该是无法到达那个页面的。

【问题讨论】:

  • 你需要一些条件,比如app.get('/protected', (req, res) => { if (req.user) { ...
  • 但是如果用户手写,他还看不到吗?例如 www.example.com/protected.html 。因为它不会去 /protected,它会去 /protected .html
  • 听起来我们这里只是在谈论授权。您可以通过在 apache auth、nginx 或使用 express 中间件(如护照)运行 Node 来实现。
  • 我认为问题不在于授权。因为 /user 和 /user.html 不一样。用户可以在工具栏中键入 html 页面的名称并再次到达那里。因为服务器控制的是 /user,而不是 /user.html。

标签: javascript html node.js express public


【解决方案1】:

创建一个自定义的static 中间件,使用中间件您可以验证路径(本案例的文件名)。

我将尝试在示例代码中用 cmets 进行解释:

// path.join here makes it work cross platform with Windows / Linux / etc
var statics = express.static(path.join(__dirname, 'public'));


function secureStatic(pathsToSecure = []) {
  return function (req, res, next) {
    if (pathsToSecure.length === 0) {
      return statics(req, res, next); // Do not secure, forward to static route
    }

    if (pathsToSecure.indexOf(req.path) > -1) {
      return res.status(403).send('<h1>403 Forbidden</h1>'); // Stop request
    }

    return statics(req, res, next); // forward to static route
  };
}


// add public files. List all "private" paths (file)
app.use(secureStatic(['admin.html'])); // instead of app.use(express.static('public'));

但是,有了这个中间件,没有人可以通过你的快递服务器请求admin.html文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 2014-11-23
    • 2012-08-28
    相关资源
    最近更新 更多