others-how to prettify the json output in nodejs or expressjs applications?

1. Purpose

In this post, I will demonstrate how to prettify the json output in nodejs or expressjs applications.



2. Solution

First let’s build a json string:

function buildReqDebugString(req,res) {
    var nowtime = getCurrentDatetime()
    var reqPath = req.originalUrl;
    var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;


    var result = {
        reqHeaders: req.headers,
        reqCookies: req.cookies,
        reqPath: reqPath,
        clientIp: ip,
        datetime: nowtime,
        resHeaders: res.header()._headers
    }
    return JSON.stringify(result,null,2)
}

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Then we can send pretty json to http response:

app.get('/hello/:name',(req,res)=>{
    var nowtime = getCurrentDatetime();
    var name = req.params.name;

    res.type('json').send(buildReqDebugString(req,res)+"\n");
});

res.type is express-js api:

res.type(type) Sets the Content-Type HTTP header to the MIME type as determined by the specified type. If type contains the “/” character, then it sets the Content-Type to the exact value of type, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the express.static.mime.lookup() method.

Here are some examples of res.type():

res.type('.html')
// => 'text/html'
res.type('html')
// => 'text/html'
res.type('json')
// => 'application/json'
res.type('application/json')
// => 'application/json'
res.type('png')
// => 'image/png'

build and run , we get this:

➜  ~ curl http://192.168.1.2:8000/test/hello/a3
{
  "reqHeaders": {
    "connection": "keep-alive",
    "x-forwarded-for": "192.168.178.16",
    "x-forwarded-proto": "http",
    "x-forwarded-host": "192.168.171.161",
    "x-forwarded-port": "8000",
    "x-forwarded-path": "/test/hello/a3",
    "x-forwarded-prefix": "/test",
    "x-real-ip": "192.168.178.16",
    "user-agent": "curl/7.64.1",
    "accept": "*/*",
    "myapi-request-id": "6dc7"
  },
  "reqCookies": {},
  "reqPath": "/hello/a3",
  "clientIp": "192.168.178.16",
  "datetime": "2022-10-19 10:53:08",
  "resHeaders": {
    "x-powered-by": "Express",
    "access-control-allow-origin": "*",
    "content-type": "application/json; charset=utf-8"
  }
}

It works!



3. Summary

In this post, I demonstrated how to prettify the json output in nodejs or expressjs applications. That’s it, thanks for your reading.