首页 > 解决方案 > 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),中间件时出现上述错误。请问我做错了什么?

标签: javascriptnode.jsexpresspugmiddleware

解决方案


推荐阅读