12
app.get('/', function(req, res){

var options = {
  host: 'www.google.com'
};

http.get(options, function(http_res) {
    http_res.on('data', function (chunk) {
        res.send('BODY: ' + chunk);
    });
    res.end("");
});

});

I am trying to download google.com homepage, and reprint it, but I get an "Can't use mutable header APIs after sent." error

Anyone know why? or how to make http call?

Johnny
  • 2,800
  • 6
  • 25
  • 33

1 Answers1

38

Check out the example here on the node.js doc.

The method http.get is a convenience method, it handles a lot of basic stuff for a GET request, which usually has no body to it. Below is a sample of how to make a simple HTTP GET request.

var http = require("http");

var options = {
    host: 'www.google.com'
};

http.get(options, function (http_res) {
    // initialize the container for our data
    var data = "";

    // this event fires many times, each time collecting another piece of the response
    http_res.on("data", function (chunk) {
        // append this chunk to our growing `data` var
        data += chunk;
    });

    // this event fires *one* time, after all the `data` events/chunks have been gathered
    http_res.on("end", function () {
        // you can use res.send instead of console.log to output via express
        console.log(data);
    });
});
blu
  • 12,905
  • 20
  • 70
  • 106
Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
  • Updated link to latest doc, this page returns high in google results. – blu Dec 27 '12 at 07:14
  • won't this eat up memory if the response is large enough? Isn't it better to write the chunks back to the response as you get them? Is that even possible? – chovy Jul 03 '13 at 23:08
  • 1
    If you are simply proxying a request, then yes streaming will be the preferred method. – Dominic Barnes Jul 04 '13 at 03:29
  • I am trying to get `var options = { host: 'en.wikipedia.org', path: '/wiki/United_Kingdom' };` but it's giving blank responce – mujaffars Oct 05 '15 at 06:04