I'm trying to send formatted json with express.
Here is my code:
var app = express(); app.get('/', function (req, res) { users.find({}).toArray(function(err, results){ // I have try both res.send(JSON.stringify(results, null, 4)); // OR res.json(results); }); });
I get the json in my browser but it's a string. How can I send it so it's readable in the browser?
If you just want to pretty print an object and not export it as valid JSON you can use console. dir() . It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets. Under the hood it is a shortcut for console.
Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.
stringify() to return JSON data): We will now use http. createServer() and JSON. stringify() to return JSON data from our server.
try to set the "secret" property json spaces
on the Node app.
app.set('json spaces', 2)
This statement above will produce indentation on json content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With