我使用收缩路线https://npmjs.org/package/shrinkroute在nodejs中建立链接。我得到错误500 ReferenceError:未定义收缩
如何将收缩路径传递给路由/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);
} 发布于 2013-12-21 13:47:26
一种解决方案是使用shrinkr将app.set存储在应用程序对象中。
// app.js
...
app.set('shrinkr', shrinkr);
...在routes/index.js中,您可以通过req.app或res.app对象访问它:
exports.showOrListUsers = function(req, res, next) {
var shrinkr = req.app.get('shrinkr');
...
};发布于 2016-07-12 23:00:32
聚会有点晚了,但以下几点也有效:
app.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;
}发布于 2013-12-26 20:11:10
实现你想要的东西有两种简单的方法:
1.从路由内访问收缩路径实例
就这么简单。设置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的作者。
https://stackoverflow.com/questions/20712712
复制相似问题