0

I am using ExpressJS..When trying to fetch value from the req.body, in the console.log(req.body[ndx])(it prints { " c o..... like this as single character)

for (var ndx in req.body){
    console.log(req.body[ndx]);
}

My req.body has the below nested JSON Object: How to extract count? req.body["count"] outputs undefined

{"count":1,"totalCount":38,"node":[{"categories":[],"foreignSource":null,"foreignId":null,"label":"172.20.96.20","assetRecord":{"description":null,"operatingSystem":null,"category":"Unspecified","password":null,"id":2655,"username":null,"vmwareManagedEntityType":null,"vmwareManagementServer":null,"numpowersupplies":null,"hdd6":null,"hdd5":null,"hdd4":null,"hdd3":null,"hdd2":null,"hdd1":null,"storagectrl":null,"thresholdCategory":null,"enable":null,"connection":null,"autoenable":null,"cpu":null,"ram":null,"snmpcommunity":null,"rackunitheight":null,"admin":null,"additionalhardware":null,"inputpower":null,"vmwareManagedObjectId":null,"vmwareState":null,"vmwareTopologyInfo":null,"circuitId":null,"assetNumber":null,"rack":null,"slot":null,"region":null,"division":null,"department":null,"building":null,"floor":null,"room":null,"vendorPhone":null,"manufacturer":null,"vendor":null,"modelNumber":null,"supportPhone":null,"maintcontract":null,"maintContractNumber":null,"maintContractExpiration":null,"displayCategory":null,"notifyCategory":null,"pollerCategory":null,"vendorFax":null,"vendorAssetNumber":null,"lastModifiedBy":"","lastModifiedDate":1433277477504,"dateInstalled":null,"lease":null,"leaseExpires":null,"managedObjectInstance":null,"managedObjectType":null,"serialNumber":null,"port":null,"comment":null},"lastCapsdPoll":1433277477793,"createTime":1433277477504,"labelSource":"A","type":"A","id":"10"}]}

My Code:

var bodyParser = require('body-parser'); 
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use('/index', function(req, res, next){
        var getReq = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            jsnArry += chunk; 
         });     
        res.on('end', function (chunk) {         
                req.body = jsnArry;
            for (var ndx in req.body){
                console.log(req.body[ndx]);
            }
            next();
        });
        }).end();
});
app.use(bodyParser.json({ type: 'application/*+json' }));   

app.use('/index', urlencodedParser, function(req, res, next){
    res.send(req.body);
     next();
});

console.log(JSON.parse(req.body)) o/p below ones

{ count: 1,
  totalCount: 38,
  node:
   [ { categories: [],
       foreignSource: null,
       foreignId: null,
       label: '172.20.96.20',
       assetRecord: [Object],
       lastCapsdPoll: 1433277477793,
       createTime: 1433277477504,
       labelSource: 'A',
       type: 'A',
       id: '10' } ] }

var options = {
          host: host,
          method: 'GET',
          headers: {
              'Accept' : 'application/json'
          }
    };

res.json(info["totalCount"]);
res.sendFile(path.join(_dirname, '/html', 'index.html'));

//Only shows the res.json value not the html page

Below is my html file:

<!DOCTYPE html>
<html data-ng-app="shopStore">
<head>
<meta charset="ISO-8859-1">
<title>Simple Angular Testing</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"></link>
<link rel="stylesheet" type="text/css" href="css/main.css"></link>
</head>
<body>
    <script type="text/javascript" src="js/lib/angular.min.js"></script>
    <script type="text/javascript" src="js/lib/d3.min.js"></script>
    <script type="text/javascript" src="js/product.js"></script>
    <script type="text/javascript" src="js/app.js"></script>

    <div data-ng-controller="scopeCtrl">
        <div data-ng-repeat="x in newRec"> 
            <p>I am product seller {{x.Name}} in {{x.City}} @ {{x.Country}}</p>
        </div>
        {{newRec[0].Name}}  
    </div>

    <div data-ng-controller="nmsCtrl">
     <p>Data to display</p>
    <!--    <div data-ng-repeat="jsn in jsnData"> 
            <p>I am product seller {{jsn.count}} displayed out of {{jsn.totalCount}}</p>
        </div> -->
    </div>  

    <div data-ng-controller="Store-Controller as store">
      <div data-ng-repeat="product in store.products">
        <div data-ng-hide='product.cantPur'>
            <h6>Product:::{{product.item}}</h6>
            <h6>Dollar Price:::{{product.dollar | currency}}</h6>
            <h6>Description::::{{product.desc}}</h6>
            <h6>{{review.stars}}</h6>
            <button data-ng-show='product.canAdd'>Add to Cart</button>
            <product-panel></product-panel>
        </div>
       </div>
    </div>
</body>
</html>
2
  • Can you output the result of console.log(typeof res.body); ? Commented Jun 13, 2015 at 17:10
  • @Pierre, It outputs String Commented Jun 13, 2015 at 17:28

2 Answers 2

1

Do you include body-parsing middleware? body-parser support JSON parsing.

var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());

bodyParser.json also expect to receive payload in application/json content type. Example using jQuery ajax:

.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
    ...
  }
})
Sign up to request clarification or add additional context in comments.

13 Comments

I am already using body-parsing middleware..This is how my code looks
My typeof req.body outputs String
how do you send the payload request? The content type should be application/json instead of application/x-www-form-urlencoded. See my edited answer.
you should use parser before the request handler. Move app.use(bodyParser.json({ type: 'application/*+json' })); to line 3.
Moved to line 3, it outputs character by character for console.log(req.body[ndx])
|
0

You probably need to convert the req.body into json using

bar myRes= JSON.parse(req.body);
console.log(myRes.count);

This should be done for you automatically. How is your bodyParser middleware set uup?

It should be set up as in the next post.

8 Comments

Nope i tried this before, its not able to indentify parse keyword itself.
Meaning you are unable to call the parse function itself?
I tried console.log(JSON.parse(chunk)) which outputs unexpected token at Object.parse
but JSON.parse(req.body) outputs value, added the o/p in my question. please check
See the edit to my post above. That doesn't do it for you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.