如何在nodejs中返回格式化的JSON对象

cod*_*ode 2 javascript json httpserver node.js

我正在制作以下nodejs服务器

var http = require('http');
var port = 1337;
http.createServer(function(req, res) {
    var statusList = {
      "hasErrors": false,
      "list" : [
        { "id": "spec1",
          "name": "retrieve blog info"
        },
        { "id": "spec2",
          "name": "Retrieve a Blog Avatar"
        },
        { "id": "spec3",
          "name": "Retrieve Blog's Likes"
        },
        { "id": "spec4",
          "name": "Retrieve a Blog's Followers"
        }
      ],
      "totalRecords": 4
    };
    console.log(req);
    console.log(statusList);
    res.writeHead(200, { 'Content-Type': 'application/json', "Access-Control-Allow-Origin":"*" });
    res.write(JSON.stringify(statusList));
    res.end();
}).listen(port);
Run Code Online (Sandbox Code Playgroud)

但这只是statusList在浏览器页面上显示没有任何格式(只是一个没有任何空格或输入的字符串).我希望json在浏览器中看到结构化格式,以便清晰可见.

我也不想在浏览器上安装任何类型的插件.

另请注意,如果我删除JSON.stringify()并只是返回对象statusList,res.write(statusList);那么我得到错误:'first argument must be a string or buffer'

Chr*_*sCM 7

试试这个:

JSON.stringify(statusList, 0, 4);
Run Code Online (Sandbox Code Playgroud)

代替.