When I run my app with NODE_ENV=test node app.js
, it returns my JSON like this:
[{"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"}]}]
When I just run node app.js
(development environment), I get JSON like this:
[
{
"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"
}
]
}
]
The code for the route doesn't change behaviour in different environments:
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);
});
};
Slightly confused why this is happening. The data is exactly the same, but the way it's getting output is different.
Check out the (relevant) source code for express
and here, too
That's just how express
works. JSON.stringify
calls get prettified if NODE_ENV
is development (which is the default value if you don't set it, by the way)
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();
});
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.