What is the difference between setting a property on app.locals and calling app.set()?

前端 未结 4 617
迷失自我
迷失自我 2021-02-05 07:09

I\'m in the process of learning Express - and thinking of the best place to save config style data. Options available are either in app.locals or app.set (settings)... so:

4条回答
  •  滥情空心
    2021-02-05 07:36

    Wow, all of the answers are wrong, so let me give it a try. Despite what others say assinging to the app.local argument is different from using app.set(). Watch,

    app.js
      app.locals.foo = 'bar';
      app.set('baz', 'quz');  
    
    
    index.jade
      block content                            
        dl                                     
          dt app.locals.foo = 'bar';            
          dd \#{settings.foo} = #{settings.foo}
          dd \#{foo} = #{foo}                  
    
          dt app.set('baz', 'quz')             
          dd \#{settings.baz} = #{settings.baz}
          dd \#{baz} = #{baz}
    

    If you ran this code, what you would see is,

    app.locals.foo = 'bar';
      #{settings.foo} =
      #{foo} = bar
    app.set('baz', 'quz')
      #{settings.baz} = quz
      #{baz} =
    

    The reason for this is setting app.locals sets attributes of the object that the view uses as its environment; what the view will read from without qualification. Conversely, app.set sets attributes on app.locals.settings. You can verify this if you clobber app.locals.settings in the above with app.locals.settings = {}, which will make #{settings.baz} undefined.

    So which do you use? If it's not an app setting based on the response (res.set) or global configuration (app.set), use the direct write to app.locals.

提交回复
热议问题