如何解决无法通过Express中的res.locals传递数据
我正在尝试将路线信息传递给每个视图。我需要在req.path
中使用index.ejs
变量。因此,我试图通过res.locals
传递数据,但是它不起作用。
我的app.js
app.use((req,res,next) => {
res.locals.path = req.path;
next();
});
router.get('/',async (req,res) => {
res.render('classes/index');
});
index.ejs
<% if(!path=='/'){ %>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a href="#" class="nav-link">Log In</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">Sign Up</a>
</li>
</ul>
<% } %>
有人看到我搞砸了吗?
解决方法
设置res.locals
的中间件应该在创建router
实例之前出现:
const router = require('express').Router();
app.use((req,res,next) => {
res.locals.path = req.path;
next();
});
router.get('/',async (req,res) => {
res.render('classes/index');
});
app.use(router);
,
您可以像这样传递数据:
router.get('/',res) => {
res.render('classes/index',{path: req.path});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。