How to Handle Global Data in ExpressJS

前端 未结 5 1339
深忆病人
深忆病人 2021-01-21 19:22

I am trying to build an express.js app and I want to pass some data to my main layout. For example, a list of navigation links that I use on every page. I know how to pass data

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-21 19:52

    You don't send vars to the layout in any special way: whatever you send to the template is accessible in the layout.

    You have a few options here:

    • you populate those vars in every request handler, meaning you'll have to duplicate the call to the function that populates those
    • you use some global variables as @garritfra suggested, meaning those vars will be application specific and not request-specific (ie: the same for all the users)
    • you create an express middleware where you'll populate those variables and apply it to the routes. I'd say this is the way to go, because that middleware can also use the global variables and can also populate the variables with request-specific info.

提交回复
热议问题