Asm Arman Asm Arman - 2 months ago 8
JSON Question

Can not get key:value from Json array

I am sending an request from my node.js server and in the console I am trying to print response data.when i tried to print the Json array.It's Ok.Like this-

{"id":1,"name":"Asm Arman","confirmed":0,"confirmation_code":null,"created_at":"2016-09-29 16:34:39","updated_at":"2016-10-04 06:55:30"}


Using this-

var request = require('request');
var app = require("express")();

app.get('/', function(req, res){
request.get('http://localhost:8000/api', function(err, response, body){

***res.send(body);
console.log(body);***

});
});

app.listen(8081);


But I can not print the key:value pair.I am getting undefined.Here is my Js file

var request = require('request');
var app = require("express")();

app.get('/', function(req, res){
request.get('http://localhost:8000/api', function(err, response, body){
var string=JSON.parse(body);
res.send(string.name);
console.log(string.name);

});
});

app.listen(8081);


Not only Json.parse() I have also used Json.stringify().But no luck.

Answer

In order to parse the body of a request, you need to use body-parser which isn't installed with Express by default. It will let you handle a body formatted with JSON, URL-encoded form values or text.

npm install body-parser --save

Then add the following to your code.

var bodyParser = require('body-parser');

// place this before your routes
app.use(bodyParser.json())