问题描述
在 Node JS 中使用嵌套路由时,我无法从正确的文件夹中获取文件。
在标准路线中,例如:
router.get('/something',(req,res) => {
res.render('something.html')
})
<img src="img/image-123.jpg">
中的这个 something.html
有效。
但是,它在使用此路线的 createProduct.html
中不起作用:
router.get('/admin/createProduct',res) => {
res.render('createProduct.html')
})
因为浏览器试图寻找不存在的 admin/img/image-123.jpg
。
我使用 index.js
app.use(require('./routes/index'))
文件中有两条路线
这些是静态文件夹:
app.use(express.static(path.join(__dirname,'/public')));
app.use(express.static(path.join(__dirname,'/uploads')));
app.use(express.static(path.join(__dirname,'scripts')));
这是我的文件结构:
如何防止这种行为?
解决方法
添加此行以访问 /admin 中子路由中的静态文件:
app.use('/admin',express.static(path.join(__dirname,'public')))