node的开发者环境设置丢失

时间:2022-11-16 08:13:12

1.我看到的最简单的一种:evn 默认的值是  development

var app = express();
if (app.get('env') === 'development') {
require('./conf');
global.Mailer = {
error: function (msg) {
console.log(msg);
}
};
console.log('load dev config');
} else {
require('./conf-online');
console.log('load online config');
var mailer = require('./utils/Mailer');
mailer.error('服务已经启动\thost:' + require('os').hostname() + '\t' + 'pid:' + process.pid + '\t' + new Date());
}

2.我们问这个env怎么设置啊?

app.set('env', 'production');

3.这个博客看一眼然后我们分析:https://segmentfault.com/q/1010000002940044

4.问为什么一个地方设置了poduction然后在另一个地方这个值又恢复默认的development

两个解决办法:

//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(, 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;

第二种方法:

****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(, 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();
}
}