0

I am using nodejs, expressjs and request to create a reverse proxy.

What I want is that when a request is sent to http://localhost:PORT/NAME/ that the corresponding page is loaded.

For example, if I enter http://localhost:1234/google/ the google website would be loaded and if I enter http://localhost:1234/stack/ the stackoverflow page would be loaded instead.

I tried code similar to the one here

var request = require('request');
app.get('/google', function(req,res) {
  //modify the url in any way you want
  var newurl = 'http://google.com/';
  request(newurl).pipe(res);
});

The problem is, that it loads the pages, but not completely, since the pages themselves wanna load images and css and stuff and make requests like /images/example.jpg And those obviously end with a 404 error.

Has anyone a handy solution for this problem? Especially since simply setting a route for /images would be no good, sinceI have two possible target servers and the proxy wouldn't know which would be the right one.

1 Answer 1

2

First of all, this is a forward proxy, second, here is a working code of what you want, modify it as you please

call this from http://127.0.0.1:5432/yahoo.com

var request = require('request');
var express = require('express')();
var session = require('cookie-session');

express.set('trust proxy', 1)
express.use(session({
  keys: ['key1', 'key2']
}))

express.use(function(req,res,next)
{
    if(req.url.indexOf('.com') < 0)
    {
        request('http://'+req.session.domain+'/'+req.params.site,function(err,response,body)
        {
            if(err)
                res.status(500).send(err);
            else
                res.send(body);
        });
    }
    else
        next();
});
express.get('/:site',function(req,res)
{
    request('http://'+req.params.site,function(err,response,body)
    {
        req.session.domain = req.params.site;
        if(err)
            res.status(500).send(err);
        else
            res.send(body);
    });
});
express.listen(5432);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.