Javascript Express中间件传递变量,错误';TypeError:无法分解属性';在中间件功能中,但通过路由定义工作
我在express中使用pug模板,并且有一个布局,其中包含我的顶部导航工具栏等。在该布局中(可在所有路线上查看),我希望在工具栏中包含一些项目的计数(理想情况下,不必包含每个页面/路线定义的请求)。所以我想我应该使用中间件 我能够使用响应Javascript Express中间件传递变量,错误';TypeError:无法分解属性';在中间件功能中,但通过路由定义工作,javascript,node.js,express,pug,middleware,Javascript,Node.js,Express,Pug,Middleware,我在express中使用pug模板,并且有一个布局,其中包含我的顶部导航工具栏等。在该布局中(可在所有路线上查看),我希望在工具栏中包含一些项目的计数(理想情况下,不必包含每个页面/路线定义的请求)。所以我想我应该使用中间件 我能够使用响应userProfile在/user视图中的页面上的任何位置,例如,但是当我尝试添加const{u raw,_json,…userProfile}=req.user时到中间件,我得到错误TypeError:Cannot destructure属性\u raw的'
userProfile
在/user视图中的页面上的任何位置,例如,但是当我尝试添加const{u raw,_json,…userProfile}=req.user时
到中间件,我得到错误TypeError:Cannot destructure属性
\u raw的'undefined'或'null'。
这与解析有关吗?请帮我理解。我正在努力减少开销,因此每个路由定义都可以,但我想了解为什么这个调用不起作用,似乎显示所有路由上您想要的信息非常有用
这只能通过视图工作(可以在布局中使用常量,但需要重新定义每条路线,这似乎很费劲)
但是这种尝试(通过中间件在所有页面上使用它)没有
app.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{{u raw,{u json,..userProfile}=json.stringify(userProfile,null,2),
时,我会得到上述错误。请问我做错了什么?请在定义了该中间件后说明如何使用该中间件谢谢您的回复,我正在我的主应用程序上使用它。jsapp.use(userInViews())代码>我将编辑以包含我的使用。我猜您正在使用passport或类似的身份验证,因为您正在尝试访问req.user
。可能发生的情况是,在userInViews
中间件之后调用创建req.user的中间件,从而使其未定义。我指的中间件是您在路由定义中进行的secured
工厂调用返回的函数。感谢您的回复,这是正确的,我使用的是passport auth0,但我认为我只使用了上述一个中间件功能?而且req.user
在/user路由上起作用-我应该在app.use(userInViews())之前创建另一个中间件函数吗代码>?我尝试使用另一个查询来mongoose,但结果相同,我只能在定义的路由上使用结果,而不能全局使用。
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();
};
};
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);