Sam Ucich
Sam Ucich

Reputation: 137

res.send not working for object?

Here's the code, htis is node.js using the express framework:


var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Expressxx' });
});

router.post('/', function(req, res, next) {

  var body = '';

  req.on('data', function(chunk) {
     body += chunk;
     });

  req.on('end', function() {
     console.log(body);
     });

  /* res.send('Got the Post'); */

  res.set('Content-Type', 'text/plain');
  res.send('this is the body' + body);
  res.end();

});

module.exports = router;

When i do the console.log(body); i see the expected data, but in the client all i see is 'this is the body'. Seems the res.send is not able to read the body obj?

Thanks....

Upvotes: 1

Views: 5781

Answers (2)

Sam Ucich
Sam Ucich

Reputation: 137

After a bit more testing, seems that res.send will send an obj if it is a Json obj...in my case its just plain text in the body obj.

When i read about this method here... http://expressjs.com/en/api.html#res.send

It says: The body parameter can be a Buffer object, a String, an object, or an Array

It didn't say it had to be a json obj???

Upvotes: 0

andyk
andyk

Reputation: 1688

The code you have above sends the response before the data event is triggered, so body is never built out. Moving the res.send and associated calls inside the end event handler should get you what you want.

Upvotes: 1

Related Questions