17

我正在使用 shrinkroute https://npmjs.org/package/shrinkroute在 nodejs 中创建链接。我收到错误 500 ReferenceError:未定义收缩器

如何将 shrinkroute 传递给 routes/index.js?有没有更好的方法通过传递查询字符串 args 来创建 url?

//app.js
var app = express();

var shrinkr = shrinkroute( app, {
    "user": {
        path: "/user/:id?",
        get: routes.showOrListUsers
    }
});
//url method works in app.js    
var url = shrinkr.url( "user", { id: 5, page:40, type:'a' } );
console.log(url);

app.use( shrinkr.middleware );

//routes/index.js
exports.showOrListUsers = function(req, res, next) {                       
    console.log(req.params); 
    //shrinkr errors out in index.js                                      
    var url2 = shrinkr.url( "users", {name: "foo"});                       
    console.log(url2);                                                                         
}      
4

4 回答 4

35

一种解决方案是使用以下方式存储shrinkr在您的应用程序对象中app.set

// app.js
...
app.set('shrinkr', shrinkr);
...

routes/index.js中,您可以通过req.apporres.app对象访问它:

exports.showOrListUsers = function(req, res, next) {
  var shrinkr = req.app.get('shrinkr');
  ...
};
于 2013-12-21T13:47:26.973 回答
11

派对有点晚了,但以下内容也有效:

应用程序.js

var my_var = 'your variable';

var route = require('./routes/index')(my_var);
app.get('/', route);

同时在route.js

var express = require('express')
,   router = express.Router()

// Router functions here, as normal; each of these
// run only on requests to the server

router.get('/', function (req, res, next) {
    res.status(200).end('Howdy');
});


module.exports = function(my_var){

    // do as you wish
    // this runs in background, not on each
    // request

    return router;
}
于 2016-07-12T23:00:32.107 回答
1

两种简单的方法来实现你想要的:

1. 从你的路由中访问你的 shrinkroute 实例

就那么简单。设置 Shrinkroute 后不需要其他任何东西。

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.使用中间件

如果你不想被 Shrinkroute 的非 URL 构建方法所吸引,你可以使用中间件,它会在你的路由和模板中为你提供一些帮助(通过本地):

// 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" } );
};

也许您也想在模板中使用它们?

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

此方法的优点是您无法直接访问路由内的路由设置器。


免责声明:我是 Shrinkroute 的作者。

于 2013-12-26T20:11:10.507 回答
0

你应该导入它。将以下行添加到代码的最开头

  var shrinkroute = require('shrinkroute');
于 2013-12-21T08:43:21.763 回答