通过Node.js路由http请求 [英] Routing http requests through Node.js

查看:203
本文介绍了通过Node.js路由http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Node.js做一个黄瓜测试设置,可以使用iframe测试任何网站。
通常,iframe是一个没有去,因为跨脚本安全限制。
但是如果可能的话(我确定是的,我相信你提出一个解决方案)
通过请求的URL获取测试的目标网站当一个特定的URL名称正在被请求,使得iframe将加载测试目标的副本。
基本上只是一个标准的node.js服务器,它基于req.url
获取特定的页面。类似于地址请求路由器。

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.

我明目张胆地试图做到这一点。
通过获取测试页。网址工程。
但是我有一个问题从http服务器切换到连接对象。
是否有一种方法可以使用http服务器响应来提供连接?

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。我还创建了一个解决方案与两个node.js服务器。
节点1获取测试目标并将其与黄瓜测试页混合。
节点2主持黄瓜测试。
此解决方案正常工作。但它会在发生JavaScript命名冲突的网站上产生问题。这是为什么iframe解决方案,通过封装解决这个问题更有吸引力。

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 + '...');


推荐答案

br>
作为node.js的新手,我不得不意识到使用多个监听器的可能性。

阅读 nodejitsu 的功能帮助我解决了这个问题。

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.

下面的示例加载www.myWebsiteToBeTestedWithCucumberJS.com
当指定url如下: http:// localhost:9788 / myWebsiteToBeTestedWithCucumberJS
其中所有其他请求作为cucumber.js网站请求处理。

希望这对其他node.js newcucumbers有意义。

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);

这篇关于通过Node.js路由http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆