请问express的app.set怎么用?在app.js使用app.set,在其他js里又恢复默认了


比如在 app.js


 var express = require('express');
var app = express();
app.set('env', 'production');
console.log(app.get('env'));//production

var routes = require('./routes/index');
app.use('/', routes);

./routes/index.js


 var express = require('express');
console.log(express().get('env'));//development

或者说,设置了环境之后,怎么读取环境?因为我看出来,在 ./routes/index.js 里用 express() 等于是新建一个 express 实例了,所以设置被重置也是正常的,但是我不知道怎么读设置好的'env'呀

Express node.js JavaScript

嘉神川丿克罗艾 9 years, 11 months ago

app.js


 var express = require('express');
var app = express();
app.set('env', 'production');
console.log('app.js', app.get('env'));//production

var routes = require('./routes/index');
app.use('/', routes);

app.listen(8080, function(){
    console.log('start ..');
})

./routes/index.js


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

router.get('/', function(req, res) {
    console.log(req.app.get('env'));//development

    res.send(req.app.get('env'));
});

module.exports = router;

clipboard.png

clipboard.png

再或者这样
app.js


 var express = require('express');
var app = express();
app.set('env', 'production');
console.log('app.js', app.get('env'));//production

var routes = require('./routes/index')(app);//传递 app 过去
app.use('/', routes);

app.listen(8080, function(){
    console.log('start ..');
})

./routes/index.js


 module.exports = function(app){
    var env = app.get('env');//从参数中获取到app,然后使用get方法
    console.log('route', env);

    return function(req, res, next){//返回一个function,以便满足 `app.js` 中 `app.use('/', routes);` 这个的用法.
        res.send(env);
        next();
    }
}

效果:

clipboard.png

clipboard.png

凤凰院彼岸 answered 9 years, 11 months ago

Your Answer