天道酬勤,学无止境

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

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 to routes/index.js? Is there a better way to create url by passing query string args?

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

评论

One solution would be to store shrinkr in your app object using app.set:

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

In routes/index.js, you can access it through the req.app or res.app objects:

exports.showOrListUsers = function(req, res, next) {
  var shrinkr = req.app.get('shrinkr');
  ...
};

A bit late to the party, but the following works as well:

app.js

var my_var = 'your variable';

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

and meanwhile in 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;
}

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.

you should import it. add following line to the very beginning of your code

  var shrinkroute = require('shrinkroute');

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Express:如何将应用程序实例传递到来自其他文件的路由?(Express: How to pass app-instance to routes from a different file?)
    问题 我想将路由分为不同的文件,其中一个文件包含所有路由,另一个文件包含相应的操作。 我目前有一个解决方案来实现此目的,但是我需要使应用程序实例成为全局实例,以便能够在操作中对其进行访问。 我当前的设置如下所示: app.js: var express = require('express'); var app = express.createServer(); var routes = require('./routes'); var controllers = require('./controllers'); routes.setup(app, controllers); app.listen(3000, function() { console.log('Application is listening on port 3000'); }); route.js: exports.setup = function(app, controllers) { app.get('/', controllers.index); app.get('/posts', controllers.posts.index); app.get('/posts/:post', controllers.posts.show); // etc. }; 控制器/ index.js: exports
  • 如何在Express中的多个文件中包括路由处理程序? [复制](How to include route handlers in multiple files in Express? [duplicate])
    问题 这个问题已经在这里有了答案: 如何在Node.js和Express 4上分开路由? (8个答案) 7天前关闭。 在我的NodeJS express应用程序中,我有一些通用路线的app.js 然后在wf.js文件中,我想定义更多路线。 如何获取app.js来识别wf.js文件中定义的其他路由处理程序? 一个简单的要求似乎不起作用。 回答1 如果要将路由放置在单独的文件中(例如, routes.js ,则可以通过以下方式创建routes.js文件: module.exports = function(app){ app.get('/login', function(req, res){ res.render('login', { title: 'Express Login' }); }); //other routes.. } 然后你就可以从需要它app.js传递app对象是这样的: require('./routes')(app); 看一下这些示例:https://github.com/visionmedia/express/tree/master/examples/route-separation 回答2 在Express 4.x中,您可以获取路由器对象的实例,并导入另一个包含更多路由的文件。 您甚至可以递归执行此操作,以便您的路由导入其他路由
  • Node.js中的module.exports与export(module.exports vs exports in Node.js)
    问题 我在Node.js模块中找到了以下合同: module.exports = exports = nano = function database_module(cfg) {...} 我不知道什么之间的不同module.exports和exports ,为什么都被用在这里。 回答1 设置module.exports允许在required时像调用函数一样调用database_module函数。 简单设置exports将不允许导出函数,因为节点将导出对象module.exports 。 以下代码不允许用户调用该函数。 module.js 以下内容无效。 exports = nano = function database_module(cfg) {return;} 如果设置了module.exports则以下内容将起作用。 module.exports = exports = nano = function database_module(cfg) {return;} 安慰 var func = require('./module.js'); // the following line will **work** with module.exports func(); 基本上, node.js不会导出exports当前引用的对象,而是导出exports最初引用的对象的属性。
  • node.js是否需要文件夹中的所有文件?(node.js require all files in a folder?)
    问题 如何在node.js的文件夹中需要所有文件? 需要类似的东西: files.forEach(function (v,k){ // require routes require('./routes/'+v); }}; 回答1 当require给出了文件夹的路径时,它将在该文件夹中寻找一个index.js文件。 如果有一个,它会使用它,如果没有,它会失败。 创建一个index.js文件,然后分配所有“模块”,然后简单地要求(如果您可以控制该文件夹),这可能是最有意义的。 yourfile.js var routes = require("./routes"); index.js exports.something = require("./routes/something.js"); exports.others = require("./routes/others.js"); 如果您不知道文件名,则应该编写某种加载程序。 装载机的工作示例: var normalizedPath = require("path").join(__dirname, "routes"); require("fs").readdirSync(normalizedPath).forEach(function(file) { require("./routes/" + file); }); //
  • 快速路由:.get()需要回调函数,但有一个[object Object](Express routes: .get() requires callback functions but got a [object Object])
    问题 好的,这对于某些人来说应该很容易指出。 我检查了其他类似的问题,但都无济于事。 我正在尝试将所有路线移至单独的routes.js文件。 在其中我有: module.exports = function (app) { var user = { list : require('./routes/user.js') } , index = { index : require('./routes/index.js') } app.get('/', function(request, response){ response.send('You made it to the home page.') }); app.get('/users', user.list); } 在我的app.js文件中,我有这个: var register_routes = require('./routes.js') register_routes(app) 我的索引路由工作正常,但会在app.get('/users', user.list); 出现此错误: .get()需要回调函数,但有一个[object Object] 这是一款开箱即用的快递应用程序,因此无需过多描述。 谢谢。 编辑:每个请求,这是./routes/user.js : exports.list = function(req, res){
  • React写后台管理注意点(使用AntDesign)
    基础姿势要过一遍吗?请点这里! react常用的ui组件库 pc antdesign 移动 antdesignMobile 蚂蚁金服 快速上手 cnpm i antd redux redux-thunk react-redux react-router-dom -S cnpm i customize-cra less less-loader node-sass -D 使用 入口函数中引入css样式文件,组件文件导入组件使用 index.js import "antd/dist/antd.css" import { Button } from 'antd'; less配置实现自定义主题 按照 配置主题 的要求,自定义主题需要用到类似 less-loader 提供的 less 变量覆盖功能。我们可以引入 craco-less 来帮助加载 less 样式和修改变量。 cnpm i @craco/craco craco-less -D 修改package.json "scripts": { "start": "craco start", "build": "craco build", "test": "craco test", } 在项目文件加下创建craco.config.js const CracoLessPlugin = require('craco-less'); module
  • Access request body in check function of express-validator v4
    I just started using express.js with express-validator to validate some input data and I have problems accessing the request body in the new check API that was introduced in version 4.0.0. In older versions, you simply added express-validator as middleware in your app.js somewhere after body-parser: // ./app.js const bodyParser = require("body-parser"); const expressValidator = require("express-validator"); const index = require("./routes/index"); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(expressValidator()); Then in my
  • Partials with Node.js + Express + Hogan.js
    I'm developing a site with Node.js + Express and using as view engine Hogan.js. This is my file app.js: /** * Module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path'); var app = express(); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'hjs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser(
  • TypeError:Router.use()需要中间件功能,但有一个Object(TypeError: Router.use() requires middleware function but got a Object)
    问题 新版本的express发生了一些中间件更改,我对此代码的其他一些帖子的代码进行了更改,但我束手无策。 我们已经事先进行了工作,但是我不记得发生了什么变化。 throw new TypeError('Router.use() requires middleware function but got a ^ TypeError: Router.use() requires middleware function but got a Object node ./bin/www js-bson: Failed to load c++ bson extension, using pure JS version js-bson: Failed to load c++ bson extension, using pure JS version /Users/datis/Documents/bb-dashboard/node_modules/express/lib/router/index.js:438 throw new TypeError('Router.use() requires middleware function but got a ^ TypeError: Router.use() requires middleware function but got a Object
  • Express routes: .get() requires callback functions but got a [object Object]
    Ok, this should be easy for somebody to point out. I checked the other similar questions and none helped. I'm trying to move all my routes to a separate routes.js file. In it I have: module.exports = function (app) { var user = { list : require('./routes/user.js') } , index = { index : require('./routes/index.js') } app.get('/', function(request, response){ response.send('You made it to the home page.') }); app.get('/users', user.list); } And in my app.js file I have this: var register_routes = require('./routes.js') register_routes(app) My index route works fine, but it kicks back on app.get(
  • URL Rewriting with ExpressJS
    I would like to rewrite my URLs on my ExpressJS website. I've used this plugin, https://github.com/joehewitt/express-rewrite, but it doesn't work... However, I might have made a mistake... My app.js file : var express = require('express') , index = require('./routes/index.js') , admin = require('./routes/admin.js') , contact = require('./routes/contact.js') , posts = require('./routes/posts.js') , http = require('http') , path = require('path') , hash = require('./auth').hash , db = require('./models') , favicons = require('connect-favicons') , rewriter = require('express-rewrite'); var app =
  • Nodejs / Express - Launching my app: express.createServer() is deprecated
    I downloaded a node app to test and play around with. I have googled around and found that Express is found to be a little outdated. Can someone help me to fix the implemented code? Here is the code /** * Module dependencies. */ // base dependencies for app var express = require('express') , routes = require('./routes') , DB = require('./accessDB').AccessDB , passport = require('passport') , mongoose = require('mongoose') , mongoStore = require('connect-mongodb'); var app = module.exports = express.createServer(); global.app = app; var DB = require('./accessDB'); var conn = 'mongodb:/
  • 在VSCode中定义多个任务(Define multiple tasks in VSCode)
    问题 我已经看到可以在VSCode中定义任务。 但是我不确定如何在tasks.json文件中定义多个任务。 回答1 以防万一它可以帮助某人...。 如果您没有/想要gulp / grunt / etc ...或额外的Shell脚本来代理您的任务命令,那么“ npm run”已经存在。 这是针对webpack和mocha的,如“构建和测试”中一样, Shift + Ctrl + B , Shift + Ctrl + T .vscode / tasks.json: { "name": "npmTask", //... "suppressTaskName": true, "command": "npm", "isShellCommand": true, "args": [ "run" ], "tasks": [ { //Build Task "taskName": "webpack", //Run On Shift+Ctrl+B "isBuildCommand": true, //Don't run when Shift+Ctrl+T "isTestCommand": false, // Show the output window if error any "showOutput": "silent", //Npm Task Name "args": [ "webpack" ], //
  • 在Express 4和express-generator的/ bin / www中使用socket.io(Using socket.io in Express 4 and express-generator's /bin/www)
    问题 所以这是交易:我正在尝试在一个快速项目中使用socket.io。 启动Express Js 4之后,我更新了express-generator,现在应用程序的初始功能进入了./bin/www文件,包括那些vars(www文件的内容:http://jsfiddle.net/avMa5/) var server = app.listen(app.get('port'), function() {..} (通过npm install -g express-generator ,然后express myApp 话虽这么说,让我们记住socket.io文档是如何要求我们将其触发的: var app = require('express').createServer(); var io = require('socket.io')(app); 好的,但是我无法像推荐的那样在app.js中执行此操作。 为了正常工作,这应该在./bin/www中完成。 在./bin/www中,这是我可以做的事情: var io = require('socket.io')(server) 好的,这行得通,但是我不能在其他任何地方使用io var,而且我真的不想将我的socket.io函数放到www文件中。 我想这只是基本语法,但我什至无法使用module.exports = server
  • koa脚手架
    Koa脚手架 koa-generator是用于生成koa项目骨架的生成器 koa-generator提供的功能如下: 生成项目骨架,集成必要的中间件 约定目录结构 项目骨架结构描述 app.js为入口 bin/www为启动入口 支持静态服务器,即public目录 支持routes路由目录 支持views视图目录 默认将Pug作为模板引擎 安装Koa生成器 koa-generator支持Koa v1和Koa v2,安装后分别使用koa和koa2命令创建koa项目模板 创建Hello worldkoa2 helloworld 安装依赖模块npm install 启动命令npm start 目录解析xxx@xxx:/mnt/c/codes/temp/hello/hello$ tree . -L 2.├── app.js├── bin│ └── www├── package.json├── public│ ├── images│ ├── javascripts│ └── stylesheets├── routes│ ├── index.js│ └── users.js└── views├── error.pug├── index.pug└── layout.pug app.js 为入口 bin/www为启动入口 支持静态服务器,即public目录 支持routes路由目录
  • 如何在Express中获取URL参数?(How to get a URL parameter in Express?)
    问题 我从我的URL: localhost:8888/p?tagid=1234获取tagid的值时tagid问题。 帮助我更正我的控制器代码。 我无法获取tagid值。 我的代码如下: app.js : var express = require('express'), http = require('http'), path = require('path'); var app = express(); var controller = require('./controller')({ app: app }); // all environments app.configure(function() { app.set('port', process.env.PORT || 8888); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); app.use
  • How to get a URL parameter in Express?
    I am facing an issue on getting the value of tagid from my URL: localhost:8888/p?tagid=1234. Help me out to correct my controller code. I am not able to get the tagid value. My code is as follows: app.js: var express = require('express'), http = require('http'), path = require('path'); var app = express(); var controller = require('./controller')({ app: app }); // all environments app.configure(function() { app.set('port', process.env.PORT || 8888); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(_
  • 与Express.js嵌套路由器一起休息(Rest with Express.js nested router)
    问题 假设我想拥有一个大致如下所示的REST端点: /user/ /user/user_id /user/user_id/items/ /user/user_id/items/item_id 在每个if上都设置CRUD是有意义的。 例如,/ user POST创建一个新用户,GET获取所有用户。 / user / user_id GET仅获取该用户。 项目是特定于用户的,因此我将它们放在特定用户user_id下。 现在,为了使Express Routing模块化,我制作了一些路由器实例。 有一个供用户使用的路由器,以及一个用于物品的路由器。 var userRouter = require('express').Router(); userRouter.route('/') .get(function() {}) .post(function() {}) userRouter.route('/:user_id') .get(function() {}) var itemRouter = require('express').Router(); itemRouter.route('/') .get(function() {}) .post(function() {}) itemRouter.route('/:item_id') .get(function() {}) app.use(
  • Nodejs全栈进阶-Vue+Express+Webpack自建脚手架完善单页面应用,档次瞬间提升(附完整源码)
    前言 阅读本文之前,可以先看看上一篇全栈入门《NodeJS全栈开发一个功能完善的Express项目(附完整源码)》,项目主要是采用前后端分离开发,前端部分使用的技术栈是基于Vue + iView,用vue-cli构建前端界面,后端部分使用的技术栈是基于Node.js + Express + MySQL,用Express搭建的后端服务器。 分享到CSDN后,受到很多小伙伴的点赞和喜欢,希望可以多出品这样的实战项目技术文章。可以让想进入Nodejs全栈开发的小伙伴提供指明灯,少走弯路,可供学习参考,减少工作量,提高工作效率。 也收到一些大佬的指点和建议,其中有位大佬,给了一些项目上的优化建议,是我曾经的同事,他看了我分享的Nodejs全栈项目后,嘴上不停的夸赞,俺瞬间脸红起来。最后却来一句,兄弟还有很大的优化升级空间哦。还是感谢各位大佬的支持,请大家也支持一下我的同事https://github.com/HEJIN2016觉得不错就给个❤️star,谢谢。 经过项目改良、优化、整合、升级后,瞬间感觉提升一个档次,开发效率也提高了。 未改良后端API接口源码地址👉:https://github.com/jackchen0120/todo-nodejs-api 未改良前端界面源码地址👉:https://github.com/jackchen0120/todo-vue-admin
  • 如何将变量从玉模板文件传递到脚本文件?(How to pass variable from jade template file to a script file?)
    问题 我在未传递到javascript文件的玉模板文件(index.jade)中声明的变量(config)遇到问题,这使我的javascript崩溃了。 这是文件(views / index.jade): h1 #{title} script(src='./socket.io/socket.io.js') script(type='text/javascript') var config = {}; config.address = '#{address}'; config.port = '#{port}'; script(src='./javascripts/app.js') 这是我的app.js(服务器端)的一部分: app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.set('address', 'localhost'); app.use(express.errorHandler({ dumpExceptions: true, showStack: true }))