【问题标题】:Handle xhr through nodejs通过nodejs处理xhr
【发布时间】:2011-08-15 00:49:23
【问题描述】:

我刚刚开始使用 nodejs,到目前为止我非常喜欢它。但是,我在使其成为中间人服务器/客户端时遇到了一些小问题。

为了澄清,我试图在客户端使用 nodejs,它将成为服务器和客户端浏览器之间的中间人。本质上,nodejs 看起来像是客户端的服务器,并且看起来像是服务器前面的客户端。 所以,我让它在 localhost 的 8080 端口上监听,并且任何传入的请求都被 nodejs 获取。

我的问题是,如何让 nodejs 在客户端浏览器中呈现请求之前对其进行分析?非常感谢任何想法/链接/帮助。

这是我拥有的简单代码:

var request = require('request'),
   http = require('http');

// var url = require('url');
// URL.parse(string);

var server = http.createServer(function (req, res) {
    var dest = req.url.substr(1, req.url.length - 1);
    //console.log(dest);
    request.get({uri: dest}, function (err, response, html) {
            console.log(html);
            console.log(response);
            res.end(html);
    });
    console.log('fetched from ' + req.url);
});

server.listen(3000);

【问题讨论】:

    标签: javascript node.js xmlhttprequest


    【解决方案1】:

    那么,你真正需要的是一个http 代理...你看过node-http-proxy 吗?它允许您自定义行为,但提供所有必需的功能,包括对 WebSockets 的支持。

    【讨论】:

      【解决方案2】:

      @alienhard 是正确的,您基本上想要一个反向代理,但我不会像他建议的那样快速找到图书馆。使用节点很容易做到这一点。

      var http = require("http")
      var util = require("util")
      
      http.createServer(function(req, rsp){
      
          var options = {
            host: 'www.google.com',
            port: 80,
            path: req.url,
            method: req.method,
            headers: req.headers
          }  
      
          proxy = http.request(options, function(response){
            rsp.writeHead(response.statusCode, response.headers)
      
            console.log(response.statusCode)
            console.log(response.headers) 
      
            response.on("data", function(chunk){ 
              console.log(chunk.toString());
              rsp.write(chunk) 
            })
      
            response.on("end", function(){ rsp.end() })
          })
      
          proxy.once("error", function(){ })
          util.pump(req, proxy)
          req.on('end', function () { proxy.end() })
      
      }).listen(3000)
      

      【讨论】:

        猜你喜欢
        • 2016-05-26
        • 1970-01-01
        • 1970-01-01
        • 2016-08-27
        • 2012-08-31
        • 2016-02-15
        • 1970-01-01
        • 2019-04-29
        • 1970-01-01
        相关资源
        最近更新 更多