Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make web service calls in Expressjs?

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?

like image 563
Johnny Avatar asked Jul 14 '11 14:07

Johnny


1 Answers

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);
    });
});
like image 80
Dominic Barnes Avatar answered Sep 19 '22 12:09

Dominic Barnes