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

时间:2014-01-03 12:17:33

标签: json node.js express

当我使用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);
  });
};

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

1 个答案:

答案 0 :(得分:2)

查看(relevant) source code for expresshere, too

这就是express的工作原理。 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(); }); }) }) 次调用会得到美化(顺便说一下,如果你没有设置它,这是默认值)

{{1}}