node.js 如何将变量从 app.js 传递到 routes/index.js?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20712712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:32:30  来源:igfitidea点击:

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

node.jsexpressshrinkroute

提问by Vlad Vinnikov

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

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

How to pass shrinkroute to routes/index.js? Is there a better way to create url by passing query string args?

如何将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);                                                                         
}      

回答by robertklep

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

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

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

In routes/index.js, you can access it through the req.appor res.appobjects:

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

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

回答by Andrew

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

聚会有点晚了,但以下也有效:

app.js

应用程序.js

var my_var = 'your variable';

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

and meanwhile in route.js

同时在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;
}

回答by gustavohenke

Two easy ways to achieve what you want:

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

1. Accessing your shrinkroute instance from within your route

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

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

就那么简单。设置 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. Using the middleware

2. 使用中间件

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):

如果您不想被 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" } );
};

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.

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

回答by Ryan Wu

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

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

  var shrinkroute = require('shrinkroute');