我想服务index.html和/media子目录作为静态文件。索引文件应该同时在/index.html和/ URLs中提供。

我有

web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));

但是第二行显然提供了整个__dirname,包括其中的所有文件(不仅仅是index.html和media),这是我不想要的。

我也试过

web_server.use("/", express.static(__dirname + '/index.html'));

但是访问基本URL /会导致对web_server/index.html/index.html (double index.html组件)的请求,这当然会失败。

什么好主意吗?


顺便说一下,我在Express中绝对找不到关于这个主题的文档(static() +它的params)…令人沮丧。文档链接也很受欢迎。


当前回答

const path = require('path');

const express = require('express');

const app = new express();
app.use(express.static('/media'));

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});

app.listen(4000, () => {
    console.log('App listening on port 4000')
})

其他回答

如果您有一个复杂的文件夹结构,例如

- application
     - assets
         - images
             - profile.jpg
     - web
     - server
        - index.js

如果你想从index.js中提供资产/图像

app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))

从浏览器查看

http://localhost:4000/images/profile.jpg

如果你需要更多的澄清评论,我会详细说明。

可以通过传递第二个参数express.static()方法来指定文件夹中的索引文件来实现这一点

const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })


在你的app.js中使用下面的方法

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

(folderName是包含文件的文件夹)-记住这些资产是直接通过服务器路径访问的(即http://localhost:3000/abc.png(其中abc.png是在folderName文件夹内)

我会在express文档中添加一些东西,有时在教程或其他地方会被误读。

app.use(mountpoint, middleware) 

挂载点是一个虚拟路径,它不在文件系统中(即使它实际存在)。中间件的挂载点是app.js文件夹。

Now

app.use('/static', express.static('public')`

会发送路径为/static/hell/meow/a.js的文件到/public/hell/meow/a.js吗

这是我在提供HTML文件链接时的错误。

之前:

<link rel="stylesheet" href="/public/style.css">

后:

<link rel="stylesheet" href="/style.css">

我只是从链接中删除了静态目录路径,错误就消失了。这解决了我的错误,还有一件事,不要忘记把这一行放在你创建服务器的地方。

var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));