How to pass variable from app.js to routes/index.js?

后端 未结 4 1722
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 13:18

I\'m using shrinkroute https://npmjs.org/package/shrinkroute to make links in nodejs. I get error 500 ReferenceError: shrinkr is not defined

How to pass shrinkroute

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 13:53

    Two easy ways to achieve what you want:

    1. Accessing your shrinkroute instance from within your route

    Simple as that. Nothing else is required after Shrinkroute is setup.

    exports.showOrListUsers = function(req, res, next) {
      var shrinkr = req.app.shrinkroute;
      console.log( "Route: " + req.route.name ); // ta-da, made available by Shrinkroute
      // do your URL buildings
    };
    

    2. Using the middleware

    If you don't want be tempted with non URL building methods of Shrinkroute, you can use the middleware, which will make available to you some helpers in your route and in your template (via locals):

    // app.js
    app.use( shrinkr.middleware );
    
    // routes/index.js
    exports.showOrListUsers = function(req, res, next) {
      console.log( "Route: " + req.route.name ); // ta-da, made available by Shrinkroute
    
      req.buildUrl( "users", { name: "foo" } );
      // or, if you want the full url with the scheme and host...
      req.buildFullUrl( "users", { name: "foo" } );
    };
    

    And maybe you want to use them in your templates as well?

    // templates/index.jade
    a( href=url( "users", { name: "foo" } ) ) Foo profile
    a( href=fullUrl( "users", { name: "foo" } ) ) Foo profile
    

    This method has the advantage that you don't get direct access to route setters inside a route.


    Disclaimer: I'm the author of Shrinkroute.

提交回复
热议问题