begineerJava begineerJava -5 years ago 154
Node.js Question

Display using request.js (node)

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

I am using this module:

This is my code :

var request = require('request');
request('', 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 Source

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(...) 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download