带有 express.js 的静态文件 [英] static files with express.js

查看:30
本文介绍了带有 express.js 的静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 index.html/media 子目录作为静态文件提供.索引文件应在 /index.html/ URL 处提供.

I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.

我有

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

但第二行显然服务于整个 __dirname,包括其中的所有文件(不仅仅是 index.htmlmedia),其中我不要.

but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.

我也试过

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

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

but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.

有什么想法吗?

顺便说一下,我在 Express 中绝对找不到关于这个主题的文档(static() + 其参数)......令人沮丧.也欢迎提供文档链接.

By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.

推荐答案

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

express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.

在 Express 文档更详细的serve-static 文档,包括服务index.html的默认行为:

Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:

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

By default this module will send "index.html" files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.

这篇关于带有 express.js 的静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆