Jackie
Jackie

Reputation: 23607

How to write to response from HTTP Client Node.JS

I have the following...

var request = require('request');

exports.list = function(req, res){
  res.send("Listing");
};
exports.get = function(req, res){
  request.get("<URL>", function (err, res, body) {
    if (!err) {
      res.send(body,"utf8");
    }
  });
};

This fails with the following....

TypeError: Object #<IncomingMessage> has no method 'send'

How do I do this?

UPDATE tried to use write instead of send but...

/Users/me/Development/htp/routes/property.js:9
  res.setHeader('Content-Type', 'text/html');
      ^
TypeError: Object #<IncomingMessage> has no method 'setHeader'

Also writing out to the console instead works fine.

Upvotes: 0

Views: 2903

Answers (3)

Plato
Plato

Reputation: 11062

I wasn't aware OP is using Express. You will encounter a similar error if you attempt to use req.send with the vanilla HTTP module instead of Express.

var http = require('http');    
function requestHandler(req, res){
  //res.send(200, '<html></html>'); // not a valid method without express
  res.setHeader('Content-Type', 'text/html');
  res.writeHead(200);
  res.end('<html><body>foo bar</body></html>');
};
http.createServer(handler).listen(3000);

Upvotes: 0

Jackie
Jackie

Reputation: 23607

Problem was with scope of variables, my response output was the same name as the response object I got back in my callback. Changing this around (resp vs res) made it work....

exports.get = function(req, res){
  request.get("<url>", function (err, resp, body) {
    if (!err) {
      res.send(body);
    }
  });
};

Upvotes: 1

moka
moka

Reputation: 23053

What you are trying to do, is to make Request > Response server. But you are using Request module, that allows to get stuff rather than respond.

What you need is http or better get express.js and use it, as it is straight forward and well popular web framework for exactly what you need.

Upvotes: 0

Related Questions