簡體   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