我想服务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)…令人沮丧。文档链接也很受欢迎。


当前回答

这是我在提供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')));

其他回答

可以通过传递第二个参数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文件夹内)

NPM安装server -index

var express    = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))

// Listen
app.listen(port,  function () {
  console.log('listening on port:',+ port );
})

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

- 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

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

这是我在提供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')));