Node.js应用中如何展示HTML文件?Express新手求助
问题:Express无法加载同目录下的index.html文件
我是Node.js新手,现有如下app.js代码:
const express = require('express'); const app = express(); const port = 8080; app.get('/', (req, res) => res.send('Hello World')); app.listen(port); console.log(`App running on http://localhost:${port}`);
同目录下还有一个包含HTML5网站的index.html文件。当前运行项目时浏览器显示Hello World,我想修改app.js使其展示该HTML文件(部署后也能显示响应式HTML),尝试了以下代码但无效果:
app.get('/',function(req,res) { res.sendFile('index.html'); });
请问该如何解决?
解决方案
使用绝对路径加载index.html
res.sendFile默认不会从当前脚本所在目录查找文件,必须传入绝对路径才能确保文件被正确找到。可以借助Node.js的__dirname全局变量(代表当前脚本的目录路径)和path模块来拼接路径:// 先引入path模块 const path = require('path'); app.get('/', function(req, res) { res.sendFile(path.join(__dirname, 'index.html')); });配置静态资源目录(保证响应式HTML依赖资源加载)
如果你的index.html中引用了CSS、JS、图片等静态资源(这些是响应式布局生效的必要条件),需要将这些资源所在的目录设置为Express的静态目录,否则浏览器无法加载这些资源:// 若静态资源和index.html在同目录下,直接配置当前目录为静态目录 app.use(express.static(__dirname)); // 如果静态资源集中放在public文件夹下,就改为: // app.use(express.static(path.join(__dirname, 'public')));完整可运行的app.js示例
const express = require('express'); const path = require('path'); const app = express(); const port = 8080; // 配置静态资源目录,确保HTML依赖的资源能被访问 app.use(express.static(__dirname)); // 根路由返回index.html app.get('/', function(req, res) { res.sendFile(path.join(__dirname, 'index.html')); }); app.listen(port); console.log(`App running on http://localhost:${port}`);
内容的提问来源于stack exchange,提问作者erenakbaba
相关产品推荐
相关产品推荐

