javascript - Express 中间件传递变量,中间件函数中出现错误“TypeError:无法解构属性”,但通过路由定义工作
问题描述
我在 express 中使用哈巴狗模板,并有一个布局,其中包含我的顶部导航工具栏等。在此布局中(在所有路线上均可查看)我想在工具栏中包含一些项目的计数(不必包含每个页面的请求/route 定义理想)。所以我想我应该使用中间件。
我可以userProfile
在 /user 视图中页面上的任何位置使用响应,例如,但是当我尝试将其添加const {_raw, _json, ...userProfile} = req.user;
到中间件时,我收到错误TypeError: Cannot destructure property
_rawof 'undefined' or 'null'.
这与解析有关吗?请帮我理解。我正在尝试减少每个路由定义的开销,但想了解为什么此调用不起作用,在所有路由上显示您想要的信息似乎非常有用。
这有效,但只能通过视图(可以在布局中使用 const 但需要重新定义每条路线,这似乎很费力),
router.get('/user', secured(), (req, res, next) => {
const {_raw, _json, ...userProfile} = req.user; // this works on routes
res.render('user', {
viewTitle: 'Profile',
userProfile: JSON.stringify(userProfile, null, 2),
});
});
但是这种尝试(通过中间件在所有页面上使用它)没有,
module.exports = function () {
return function (req, res, next) {
const { _raw, _json, ...userProfile } = req.user;
res.locals = {
userProfile: JSON.stringify(userProfile, null, 2), // gives error in middleware but works in routes
// userProfile: req.user, // tried this too //
user: req.user,
token: '1234',
isAuthenticated: req.isAuthenticated(),
};
next();
};
};
应用程序.js
app.use(express.json());// sets content-type to json
app.use(userInViews());
app.use('/', authRouter);
app.use('/', indexRouter);
app.use('/', usersRouter);
app.use('/', postRoutes);
app.use('/calendar', calendarRouter);
app.use('/bookings', usersRouter);
app.use('/add', usersRouter);
app.use('/edit', usersRouter);
app.use('/list', usersRouter);
app.use('/delete', usersRouter);
app.use('/calendar', usersRouter);
app.use('/dashboard', usersRouter);
app.use('/search', usersRouter);
app.use('/user', usersRouter);
为什么我可以获取其他变量并在所有路由的中间件中使用它们,但是在调用const { _raw, _json, ...userProfile } = JSON.stringify(userProfile, null, 2),
中间件时出现上述错误。请问我做错了什么?
解决方案
推荐阅读
- google-workspace - 应用程序脚本联系人 api 同步问题
- sql-server - 许多“多对多”的冗余
- python - 如何使用 PyMongo 在 python 中执行通配符搜索 mongoDB
- r - 使用 DPLYR 在 R 中组合多个操作
- unix - 当我定向到文件时,awk 冻结
- node.js - 如何通过 Cloud Foundry 部署“正确”减少停机时间?
- c# - 设置实体框架时的多重性冲突
- python - 根据按 ID 分组的类别计算列中的值差异
- r - 将两个具有相同 X 向量的 ggplots 组合起来是不好的做法/风格吗?
- docker - 通过多个 Docker 容器监听同一个端口