app.js中的全局变量可以在路由中访问? [英] Global Variable in app.js accessible in routes?

查看:187
本文介绍了app.js中的全局变量可以在路由中访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 app.js 中设置一个变量,并在所有路径中都可用,至少在 index.js 文件位于路线。使用明确的框架和 node.js

How do i set a variable in app.js and have it be available in all the routes, atleast in the index.js file located in routes. using the express framework and node.js

推荐答案

变量,只是声明它没有 var 关键字。 (一般来说,这不是最佳实践,但在某些情况下它可能是有用的 - 只需要小心,因为它将使变量在任何地方可用。)

To make a global variable, just declare it without the var keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.)

这是一个例子来自 visionmedia / screenshot-app

文件 app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , stylus = require('stylus')
  , redis = require('redis')
  , http = require('http');

app = express();

//... require() route files

文件> routes / main.js

file routes/main.js

//we can now access 'app' without redeclaring it or passing it in...

/*
 * GET home page.
 */

app.get('/', function(req, res, next){
  res.render('index');
});

//...

这篇关于app.js中的全局变量可以在路由中访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆