📅  最后修改于: 2023-12-03 15:04:53.626000             🧑  作者: Mango
res.locals
is a useful property in the Express framework for Node.js. It provides an object to store data that can be passed between middleware. In this article, we will dive into what res.locals
is and how to use it in your application.
res.locals
is an object that is available to all middleware functions in Express. It is an empty object by default, allowing you to add your own custom properties to it.
app.use(function(req, res, next) {
res.locals.userName = "John Doe";
res.locals.age = 30;
next();
});
You can use res.locals
in any middleware function such as app.use
, app.get
, app.post
and so on.
app.get('/', function(req, res) {
res.locals.title = "Home";
res.render('home', { pageTitle: res.locals.title });
});
In the above example, the title
property is set in the middleware and then passed to the view engine using res.render
.
One of the most common use cases for res.locals
is to pass data to the view engine. Here is an example using the EJS view engine.
app.set('view engine', 'ejs');
app.use(function(req, res, next) {
res.locals.title = "My Website";
next();
});
app.get('/', function(req, res) {
res.render('home');
});
The value of title
will be available in the view as a local variable.
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome to <%= title %></h1>
</body>
</html>
res.locals
is a powerful tool that allows you to store data and pass it between middleware functions. It is also very useful when working with view engines, as it allows you to pass data to the view. We hope this article has helped you understand how to use res.locals
in your Express application.