Express配置public静态目录仅index.html可访问 其他页面报错如何解决
错误原因
res.sendFile方法传入以/开头的路径时,默认会从操作系统的根目录开始查找文件,而非你的项目目录,因此会提示找不到/page1.html文件。你之前访问/路由正常是因为express.static中间件会默认返回public目录下的index.html,优先级高于你手写的/路由回调。
修复方案
方案1:拼接正确的绝对路径(推荐)
引入Node内置的path模块,用__dirname(当前app.js所在的目录)拼接出目标文件的绝对路径,修改后的app.js代码如下:
const express = require('express') const path = require('path') const app = express() app.use(express.static('public')) app.get('/', function(req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); app.get('/pageone', function(req, res) { res.sendFile(path.join(__dirname, 'public', 'page1.html')); }); app.get('/pagetwo', function(req, res) { res.sendFile(path.join(__dirname, 'public', 'page2.html')); }); app.listen('8000', function() { console.log("Server is running on port 8000.") })
方案2:利用静态资源中间件做重定向
你已经配置了express.static中间件,public目录下的文件可以直接通过文件名访问,因此可以直接把自定义路由修改为重定向逻辑:
app.get('/pageone', function(req, res) { res.redirect('/page1.html') }) app.get('/pagetwo', function(req, res) { res.redirect('/page2.html') })
内容的提问来源于stack exchange,提问作者HalfMillennium
相关产品推荐
相关产品推荐

