簡體   English   中英

通過nodejs處理xhr

[英]Handle xhr through nodejs

我剛開始使用 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);

所以,你真正需要的是一個http 代理......你看過node-http-proxy嗎? 它允許您自定義行為,但提供所有必需的功能,包括對 WebSockets 的支持。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM