Axon Axon - 1 month ago 4
Javascript Question

Expressjs res.json renders html and json in body

I have router sending json data to the client like this:

router.get('/', function(req, res, next) {
UserModel.selectAllUsers(function(err, vals){
res.json({d: vals});

When i visit route in browser i get valid json printed out:


but when i inspect view in browser developer tools I see:

<pre style="word-wrap: break-word; white-space: pre-wrap;">{"d": [{"id":1,"name":"arian","sex":"male","race":"caucassian"},{"id":2,"name":"eni","sex":"female","race":"caucassian"}]}</pre>

Shouldn't res.json() set content type to application/json? Why I'm getting JSON wrapped in html?


Most browsers don't have a separate renderer specifically for JSON (or any other content type, for that matter). To present the JSON without it being formatted incorrectly, browsers like Chrome present it as text wrapped in a styled HTML pre tag. You'll notice the same if you load an image file, - the HTML will just be an image tag with the source set to that URL.

To see what's actually being transmitted by your server, you can open up the developer tools of your browser. In Chrome you can press F12 and then go to the "Network" tab where all of your requests and their contents will be listed.