javascript Express.js - 如何修改路由中的 app.locals 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31634646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:06:25  来源:igfitidea点击:

Express.js - How to Modify app.locals variables in routes

javascriptnode.jsexpress

提问by Sohrab Hejazi

I have a node.js project. The following code is part of my app.js file. I'm making a query from the database and storing the results in a global variabled called 'Cats'. I'm using this variable to display the categories on a sidebar of the site. I don't think its relevant but I am using Jade as templating engine.

我有一个 node.js 项目。以下代码是我的 app.js 文件的一部分。我正在从数据库进行查询并将结果存储在名为“Cats”的全局变量中。我正在使用此变量在站点的侧边栏上显示类别。我不认为它相关,但我使用 Jade 作为模板引擎。

var app = express()

var query = "SELECT * FROM findadoc.categories";
client.execute(query, [], function(err, results) {
  if(err) {
    res.status(404).send({meg: err});
  }
  else {
    app.locals.cats = results.rows;
  }
});

In one of the routes, I allow the user to add additional category to the database. What I need is for the 'apps.locals.cats' variable to get updated with the new set of categories. Is there anyway for me to modify this in my routes? I tried the following but it didn't work.

在其中一个路由中,我允许用户向数据库添加其他类别。我需要的是让 'apps.locals.cats' 变量使用新的类别集进行更新。无论如何我可以在我的路线中修改它吗?我尝试了以下但没有奏效。

router.post('/add', function(req, res, next) {
    var cat_id = cassandra.types.uuid();
    var query = "INSERT INTO findadoc.categories(cat_id, name) VALUES (?,?)";
    client.execute(query, [cat_id, req.body.name], {prepare: true},   function(err, results) {
        if(err) {
            res.status(404).send({msg: err});
        } 
        else {
            cats = results.rows;
            req.flash('success', "Category Added");
            res.location('/doctors');
            res.redirect('/doctors');
        }
    });
});

回答by Carlos

In Express 4 You can access to appfrom reqwith req.app. See Request objectAPI doc.

在快递4您可以访问app来自reqreq.app。请参阅请求对象API 文档。

Locals are available in middleware via req.app.locals (see req.app)

本地变量通过 req.app.locals 在中间件中可用(参见 req.app)

In your middleware you could do it as this:

在您的中间件中,您可以这样做:

router.post('/add', function(req, res, next) {
    // do some cool stuff
    req.app.locals.cats = something;
    // more cool stuff
});