最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do i return the formatted JSON object in nodejs - Stack Overflow

programmeradmin0浏览0评论

I am making the following nodejs server

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);

But this simply display statusList without any format (simply as a string without any space or enter) on the browser page. I want to see the structured formatted json in browser so that it is clearly visible.

I also don't want to install any kind of plugin on my browser.

Also note that if i remove JSON.stringify() and simply return the object statusList as res.write(statusList); then i get the error : 'first argument must be a string or buffer'

I am making the following nodejs server

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);

But this simply display statusList without any format (simply as a string without any space or enter) on the browser page. I want to see the structured formatted json in browser so that it is clearly visible.

I also don't want to install any kind of plugin on my browser.

Also note that if i remove JSON.stringify() and simply return the object statusList as res.write(statusList); then i get the error : 'first argument must be a string or buffer'

Share Improve this question asked Aug 7, 2013 at 18:03 codeofnodecodeofnode 18.6k29 gold badges88 silver badges146 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Try this:

JSON.stringify(statusList, 0, 4);

Instead.

发布评论

评论列表(0)

  1. 暂无评论