Express中app.locals和res.locals

Express应用中的app.locals对象提供全局变量,其值在应用生命周期内有效,可在模板中访问。res.locals对象则包含请求级别的局部变量,仅在当前请求/响应周期内有效,适用于暴露请求级信息。这两个属性都可以传递到渲染的视图中,但作用范围和生命周期不同。
摘要由CSDN通过智能技术生成

1.app.locals

The app.locals object has properties that are local variables within the application.

app.locals.title
// => 'My App'

app.locals.email
// => 'me@myapp.com'

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via req.app.locals (see req.app)

app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';

2.res.locals

An object that contains response local variables scoped to the request, a

var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); const UserRouter = require('./routes/admin/UserRouter'); const JWT = require('./util/JWT'); const NewsRouter = require('./routes/admin/NewsRouter'); const webNewsRouter = require('./routes/web/NewsRouter'); const ProductRouter = require('./routes/admin/ProductRouter'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/users', usersRouter); app.use(webNewsRouter) /* /adminapi/* - 后台系统用的 /webapi/* - 企业官网用的 */ app.use((req, res, next) => { // 如果token有效 ,next() // 如果token过期了, 返回401错误 if (req.url === "/adminapi/user/login") { next() return; } const token = req.headers["authorization"].split(" ")[1] if (token) { var payload = JWT.verify(token) // console.log(payload) if (payload) { const newToken = JWT.generate({ _id: payload._id, username: payload.username }, "1d") res.header("Authorization", newToken) next() } else { res.status(401).send({ errCode: "-1", errorInfo: "token过期" }) } } }) app.use(UserRouter) app.use(NewsRouter) app.use(ProductRouter) // catch 404 and forward to error handler app.use(function (req, res, next) { next(createError(404)); }); // error handler app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
最新发布
07-15
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值