如何使用ExpressJS访问public文件夹中除index.html外的其他HTML页面
Express 访问public目录下非index.html静态页面的解决方案
问题原因
- 你自定义的
/createelection路由会覆盖静态资源的无后缀匹配逻辑:当你请求/createelection路径时,express.static中间件找不到无后缀的匹配资源,会向下触发你定义的这个路由,该路由仅打印日志没有返回任何页面内容,导致无法正常加载页面 express.static默认要求请求路径带完整文件后缀才能匹配对应静态文件
解决方案
方案1:直接带后缀访问(无需修改代码)
直接在浏览器访问带.html后缀的路径即可正常打开对应页面:
- 首页:
http://localhost:3000或http://localhost:3000/index.html - 选举创建页:
http://localhost:3000/createelection.html - 选民登录页:
http://localhost:3000/voterlogin.html
方案2:配置无后缀访问(符合常规路由使用习惯)
方式A:修改static中间件配置(推荐,无需逐个写路由)
给express.static添加extensions参数,自动匹配html后缀文件:
// 把原来的 app.use(express.static(static_path)); 改成下面的代码 app.use(express.static(static_path, { extensions: ['html'] }));
配置完成后直接访问http://localhost:3000/createelection、http://localhost:3000/voterlogin即可打开对应页面。
注意:如果用这个方式,可以把你自定义的app.get('/createelection')空路由删除,避免路由冲突
方式B:手动定义路由映射
如果需要在路由触发时执行额外逻辑(比如打印日志、权限校验),可以修改你的自定义路由,手动返回对应HTML文件:
app.get('/createelection',(req,res)=>{ console.log("Create an Election here"); // 返回对应HTML文件 res.sendFile(path.join(static_path, 'createelection.html')); }); // 同理补充选民登录页的路由 app.get('/voterlogin',(req,res)=>{ res.sendFile(path.join(static_path, 'voterlogin.html')); });
内容的提问来源于stack exchange,提问作者Sphynx
相关产品推荐
相关产品推荐

