繁体   English   中英

不同的NODE_ENV返回相同的数据但“输出不同”

[英]Different NODE_ENV's returns same data but 'different' output

当我使用NODE_ENV=test node app.js运行我的应用程序时,它返回我的JSON,如下所示:

[{"title":"Pancakes","description":"The best pancakes!","readyIn":"20 min","method":"To make the best pancakes do this..","_id":"52c1eca507becc63ed000002","ingredients":[{"name":"eggs","amount":"2"},{"name":"plain flour","amount":"100g"},{"name":"milk","amount":"300ml"}]}]

当我运行node app.js (开发环境)时,我得到这样的JSON:

[
  {
    "title": "Pancakes",
    "description": "The best pancakes!",
    "readyIn": "20 min",
    "method": "To make the best pancakes do this..",
    "_id": "52c6ab0e696daa0000000002",
    "ingredients": [
      {
        "name": "eggs",
        "amount": "2"
      },
      {
        "name": "plain flour",
        "amount": "100g"
      },
      {
        "name": "milk",
        "amount": "300ml"
      }
    ]
  }
]

路由的代码不会改变不同环境中的行为:

app.get('/recipes', recipe.all);

exports.all = function(req, res) {
  Recipe.all(function(err, recipes) {
    if(err) return res.json(500, 'Internal Server Error');
    if(recipes === null) recipes = {};
    return res.json(200, recipes);
  });
};

Recipe.prototype.all = function(callback) {
  RecipeModel.find({}, function(err, recipes) {
    if(err) return(err, null);
    return callback(null, recipes);
  });
};

稍微混淆了为什么会发生这种情况。 数据完全相同,但获得输出的方式不同。

查看express(相关)源代码 也在这里

这就是express方式。 如果NODE_ENV是开发的话, JSON.stringify调用会被NODE_ENV (如果你没有设置它,这是默认值)

describe('"json spaces" setting', function(){
  it('should default to 2 in development', function(){
    process.env.NODE_ENV = 'development';
    var app = express();
    app.get('json spaces').should.equal(2);
    process.env.NODE_ENV = 'test';
  })

  it('should be undefined otherwise', function(){
    var app = express();
    assert(undefined === app.get('json spaces'));
  })

  it('should be passed to JSON.stringify()', function(done){
    var app = express();

    app.set('json spaces', 2);

    app.use(function(req, res){
      res.json({ name: 'tobi', age: 2 });
    });

    request(app)
    .get('/')
    .end(function(err, res){
      res.text.should.equal('{\n  "name": "tobi",\n  "age": 2\n}');
      done();
    });
  })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM