Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing http requests through Node.js

I'm trying to make a cucumber test setup with Node.js that can test any website by using an iframe. Normally the iframe is a no go because of cross script security limitations. However if it was possible (I'm sure it is. And i trust you to come up with a solution) to fetch the website being target for the test via the requested url when a specific url name is being requested, so that the iframe would be loaded with a copy of the test target. Basically just a standard node.js server that fetches specific pages based on the req.url Akin to an Address Request Router.

Here is my blatant attempt to do exactly that. Fetching the test page via. the url works. But i'm having a problem switching from the http server to the connection object. Is there a way to "feed" the connection with the http server response?

PS. i also created a solution with two node.js servers. Node 1 fetched the test target and mixing it with cucumber test page. Node 2 hosting the cucumber test. This solution is working. But it creates problems on websites where javascript naming conflicts occur. Which is why the iframe solution, that solves this problem by encapsulation is more appealing.

var http  = require('http');
var connect    = require('connect');
var port  = process.env.PORT || 8788;

var server = http.createServer(function(req, webres)
{
    var url = req.url;
    console.log(url);

    if(url == '/myWebsiteToBeTestedWithCucumberJS')
    {
        // Load the web site to be tested "myWebsiteToBeTestedWithCucumberJS"
            // And update the references
            // Finaly write the page with the webres
            // The page will appear to be hosted locally

        console.log('Loading myWebsiteToBeTestedWithCucumberJS');
        webres.writeHead(200, {'content-type': 'text/html, level=1'});
        var options =
        {  
                   host: 'www.myWebsiteToBeTestedWithCucumberJS.com,   
                   port: 80,   
                   path: '/'
        };

        var page = '';
        var req = http.get(options, function(res)
        {
            console.log("Got response: " + res.statusCode);   
            res.on('data', function(chunk)
            {
                page = page + chunk;
            });   
            res.on('end', function()
            {
                    // Change relative paths to absolute (actual web location where images, javascript and stylesheets is placed)
                    page = page.replace(/ href="\/\//g       , ' href="/');
                    page = page.replace(/ src="\//g          , ' src="www.myWebsiteToBeTestedWithCucumberJS.com');
                    page = page.replace(/ data-src="\//g     , ' data-src="www.myWebsiteToBeTestedWithCucumberJS.com');
                    page = page.replace(/ href="\//g         , ' href="www.myWebsiteToBeTestedWithCucumberJS.com');

                    webres.write(page);
                    webres.end('');
            });
        });
    }
    else
    {
        // Load any file from localhost:8788
            // This is where the cucumber.js project files are hosted
        var dirserver     = connect.createServer();
        var browserify = require('browserify');
        var cukeBundle = browserify({
          mount: '/cucumber.js',
          require: ['cucumber-html', './lib/cucumber', 'gherkin/lib/gherkin/lexer/en'],
          ignore: ['./cucumber/cli', 'connect']
        });
        dirserver.use(connect.static(__dirname));
        dirserver.use(cukeBundle);
        dirserver.listen(port);
    }
}).on('error', function(e)
{  
      console.log("Got error: " + e.message);   
});
server.listen(port);
console.log('Accepting connections on port ' + port + '...');
like image 958
DevNull Avatar asked Oct 08 '22 01:10

DevNull


1 Answers

Well it wasn't so difficult after all.
Being new to node.js i had to realize the possibilties of using multiple listeners.
Reading on nodejitsu's features helped me solve the problem.

Below example loads www.myWebsiteToBeTestedWithCucumberJS.com when specifying the url as follows: http://localhost:9788/myWebsiteToBeTestedWithCucumberJS where all other requests is handled as cucumber.js website requests.
Hope this make sense to other node.js newcucumbers.

var http  = require('http');

var connect    = require('connect');
var port  = process.env.PORT || 9788;

var server = http.createServer(function(req, webres)
{
    var url = req.url;
    console.log(url);
    if(url == '/myWebsiteToBeTestedWithCucumberJS')
    {
        loadMyWebsiteToBeTestedWithCucumberJS(req, webres);
    }
    else
    {
        loadLocal(req, webres, url);
    }
}).on('error', function(e)
{  
      console.log("Got error: " + e.message);   
});
server.listen(port);
console.log('Accepting connections on port ' + port + '...');

function loadMyWebsiteToBeTestedWithCucumberJS(req, webres)
{
    console.log('Loading myWebsiteToBeTestedWithCucumberJS');
    webres.writeHead(200, {'content-type': 'text/html, level=1'});
    var options =
    {  
               host: 'www.myWebsiteToBeTestedWithCucumberJS.com',   
               port: 80,   
               path: '/'
    };

    var page = '';
    var req = http.get(options, function(res)
    {
        console.log("Got response: " + res.statusCode);   
        res.on('data', function(chunk)
        {
            page = page + chunk;
        });   
        res.on('end', function()
        {
                page = page.replace(/ href="\/\//g       , ' href="/');
                page = page.replace(/ src="\//g          , ' src="http://www.myWebsiteToBeTestedWithCucumberJS.com/');
                page = page.replace(/ data-src="\//g     , ' data-src="http://www.myWebsiteToBeTestedWithCucumberJS.com/');
                page = page.replace(/ href="\//g         , ' href="http://www.myWebsiteToBeTestedWithCucumberJS.com/');

                webres.write(page);
                webres.end('');
        });
    });

}

function loadLocal(req, webres, path)
{
    console.log('Loading localhost');
    webres.writeHead(200, {'content-type': 'text/html, level=1'});
    var options =
    {  
               host: 'localhost',   
               port: 9787,   
               path: path
    };

    var page = '';
    var req = http.get(options, function(res)
    {
        console.log("Got response: " + res.statusCode);   
        res.on('data', function(chunk)
        {
            page = page + chunk;
        });   
        res.on('end', function()
        {
                webres.write(page);
                webres.end('');
        });
    });
}


// Cucumber site listening on port 9787
var dirserver     = connect.createServer();
var browserify = require('browserify');
var cukeBundle = browserify(
{
    mount: '/cucumber.js',
    require: ['cucumber-html', './lib/cucumber', 'gherkin/lib/gherkin/lexer/en'],
    ignore: ['./cucumber/cli', 'connect']
});
dirserver.use(connect.static(__dirname));
dirserver.use(cukeBundle);
dirserver.listen(9787);
like image 86
DevNull Avatar answered Oct 09 '22 19:10

DevNull