begineerJava begineerJava - 5 months ago 14
Node.js Question

Display google.com using request.js (node)

I want to make a simple HTTP proxy , so when you hit http://localhost:8000/, you should get google.co.uk.

I am using this module: https://github.com/request/request

This is my code :

var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})


When I do 'node node.js' (node.js is my file name), I get the body printed in the git bash, but when I try to open the localhost it is unavailable.

What am I doing wrong?

Answer

You need to create a server, eg with http, express, ...

#!/usr/bin/env node
var request = require('request');
var http = require('http');
var server = http.createServer(function(req, res) {
  request('http://www.google.com').pipe(res);
});
server.listen(1234);

request(...) returns a read stream you can pipe to the response write stream you get from creating said server.

I jammed a lot of interesting links into the answer, I would recommend you read up on how streams work in node.