简体   繁体   中英

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM