【问题标题】:Express routes to serve directory of static content快速路由以提供静态内容目录
【发布时间】:2020-07-07 18:30:40
【问题描述】:

我对 NodeJs 和 Express 非常陌生。 这是我的目录结构:

.
├── app.js
├── package-lock.json
├── package.json
├── views
│   ├── login.ejs
│   └── partials
│       ├── footer.ejs
│       └── header.ejs
└── www
    ├── anchor.html
    └── index.html

我正在尝试使用 app.get 创建快速路由来加载“www”目录的内容,但动态加载 我用 res.sendFile:

app.get("/mypath", function(req, res){
  res.sendfile(__dirname + '/www/');
});

但是它只允许我提供单个 index.html 文件,并且在 index.html 文件中是指向另一个 html 文件“anchor.html”的锚链接,但它不会加载该文件。

是否有与 sendFile 等效的方法可以让我将“www”的整个目录提供给 get 路由?

【问题讨论】:

  • 所以您的问题是:“我如何使用 express 提供静态内容?”
  • 是的,但它的整个目录到特定的路由路径。

标签: html node.js express web


【解决方案1】:

阅读文档:https://expressjs.com/en/starter/static-files.html

app.use(express.static(path.join(__dirname, 'public')));

上面的sn-p会静态服务public/下的所有文件

【讨论】:

  • 谢谢,我想到了这个,但是在快速路线中如何使用呢?
  • 我不明白这个问题。你是说:“我如何访问这些静态文件之一”?
  • 所以我想设置多个快速路由,例如:/path1 ---->/www 目录中的静态文件,然后 /path2 -----另一个目录中的静态文件
  • 也就是说在 app.get 中使用我如何提供 www 目录中的任何内容
【解决方案2】:

可以添加挂载路径:

app.use('/path1', express.static(__dirname + '/www'));            // Serves files as named in the '/path1' url path
app.use('/path2', express.static(__dirname + '/otherdirectory')); // Serves files as named in the '/path2' url path

例如,如果你想访问 /www 目录中的 index.html,你会去 (假设您在 localhost 端口 80 上托管 Web 应用程序)localhost/path1/index.html。

【讨论】:

  • 是否可以在 app.get 之类的路由路径中使用它?所以我希望将静态 html 文件作为我的 app.get 的功能作为响应?如果可能的话,你能提供它的例子吗?
  • 当然,你可以这样做,但那样会更乏味。您必须为每个文件创建一个路由。 example
  • 是的,那是我的恐惧,我可能有数百个文件要提供。
猜你喜欢
  • 2021-12-10
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多