Difference between assigning to res and res.locals in node.js (Express)

后端 未结 1 925
长情又很酷
长情又很酷 2020-12-24 12:37

Hi I have some newbie questions about the use of res (Express response object) and res.locals in Express.

While studying nodejs in one of the code examples There is

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 13:21

    res.locals is an object passed to whatever rendering engine your app is using (in this case ejs). They'll be 'global' in the render, so you don't need to prepend anything on to them to use them.

    Say we wanted our server to pick up our JavaScript from S3 when in production mode, but use the local copies when in development. res.locals makes this easy. We'd have middleware along these lines in app.js:

    if ('production' === app.get('env')) {
      res.locals.jsLocation = 'https://s3.amazonaws.com/kittens/js/'
    } else {
      res.locals.jsLocation = '/js/';
    }
    

    and index.ejs would be something like this:

    
    
    

    0 讨论(0)
提交回复
热议问题