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


当前回答

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

- 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

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

其他回答

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

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

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

在express的最新版本中,“createServer”已弃用。这个例子很适合我:

var express = require('express');
var app = express();
var path = require('path');

//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root

app.listen(80);
console.log('Listening on port 80');

static()期望第一个参数是目录的路径,而不是文件名。我建议创建另一个子目录来包含index.html并使用它。

在Express文档中提供静态文件,或者更详细的服务静态文档,包括提供index.html的默认行为:

默认情况下,该模块将发送“index.html”文件以响应对目录的请求。若要禁用此设置false或提供一个新索引,则按首选顺序传递一个字符串或数组。

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

- 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')));