user1997649
user1997649

Reputation: 23

node.js simple proxy server

i'm trying to implement simple anonymous http proxy server in nodejs

var http = require('http'),
    request = require('request');
http.createServer(function(req,res){
    req.pipe(request(req.url)).pipe(res)
}).listen(8888)

i'm recieving the following error:

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
Error: CERT_HAS_EXPIRED
    at SecurePair.<anonymous> (tls.js:1370:32)
    at SecurePair.EventEmitter.emit (events.js:92:17)
    at SecurePair.maybeInitFinished (tls.js:982:10)
    at CleartextStream.read [as _read] (tls.js:469:13)
    at CleartextStream.Readable.read (_stream_readable.js:320:10)
    at EncryptedStream.write [as _write] (tls.js:366:25)
    at doWrite (_stream_writable.js:226:10)
    at writeOrBuffer (_stream_writable.js:216:5)
    at EncryptedStream.Writable.write (_stream_writable.js:183:11)
    at write (_stream_readable.js:583:24)
    at flow (_stream_readable.js:592:7)
    at Socket.pipeOnReadable (_stream_readable.js:624:5)

Here is another error:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Invalid protocol

Any suggestions?

Upvotes: 0

Views: 631

Answers (2)

Leonid Beschastny
Leonid Beschastny

Reputation: 51490

req.url is a relative path, not a full url. It means that you should add protocol and domain name to it:

req.pipe(request('http://mydomain.com'+req.url)).pipe(res)

You're also forgetting about req.method and req.headers:

req.pipe(request({
  url: 'http://mydomain.com'+req.url,
  method: req.method,
  headers: req.headers
})).pipe(res)

If your purpose is to use it as a real proxy server, then I would recommend you to look at node-http-proxy - it's a perfect node.js proxy server implementation.

If you just want to learn node.js, then look at this article with example proxy server implementation. Author of the article is using build-in http module to send request instead of more powerful request module and not using piping, but the rest of the article looks fine.

As for you first problem, Piotr Tomasik's answer should help you.

Upvotes: 3

Piotr Tomasik
Piotr Tomasik

Reputation: 9194

Looks like the domain you are hitting has an expired cert.

Add this to the top of your file.

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

As for your second error, make sure that the url includes the protocol. http https

Upvotes: 1

Related Questions