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:

    var nowtime = getCurrentDatetime();
    var name = req.params.name;


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():

// => 'text/html'
// => 'text/html'
// => 'application/json'
// => 'application/json'
// => 'image/png'

build and run , we get this:

➜  ~ curl
  "reqHeaders": {
    "connection": "keep-alive",
    "x-forwarded-for": "",
    "x-forwarded-proto": "http",
    "x-forwarded-host": "",
    "x-forwarded-port": "8000",
    "x-forwarded-path": "/test/hello/a3",
    "x-forwarded-prefix": "/test",
    "x-real-ip": "",
    "user-agent": "curl/7.64.1",
    "accept": "*/*",
    "myapi-request-id": "6dc7"
  "reqCookies": {},
  "reqPath": "/hello/a3",
  "clientIp": "",
  "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.