如何接收HTTP请求,修改主体,然后发布到另一个端点?

时间:2014-06-27 13:47:30

标签: node.js

我正在尝试编写一个简单的服务

  1. 收到http请求
  2. 修改正文中的一些值
  3. 然后,将数据(标题+新修改的主体)发布到另一个端点。
  4. 将新请求的确切回复返回给客户。
  5. 我找到了一个很好地进行http中继的示例,但是在发送之前我正在努力修改帖子?我能够获得帖子的内容,但似乎可以在发送之前了解如何修改它。

    var http = require( 'http' );
    var qs = require( 'querystring' );
    
    http.createServer( function ( req, resp ) {
    
        var h = req.headers;
    
        h.host = "webdbg.com";
        req.url = "/sandbox/FileForm.asp";
    
        var newRequest = http.request( {
            host: h.host, port: 80, path: req.url, method: req.method, headers: h
        }, function ( newResp ) {
                resp.writeHead( newResp.statusCode, newResp.headers );
                //as we receive our response from the new request, start writing it to this response.
                newResp.on( 'data', function ( respBody ) { resp.write( respBody ); });
                //once we have all the data from the new request stor writing it to this response.
                newResp.on( 'end', function () { resp.end(); });
            });
    
        var postData = "";
        //as we receive our body write it to the new request.
        req.on( 'data', function ( reqBody ) { postData += reqBody;  newRequest.write( reqBody )});//here I need to replace the values of the form post 
        //once we have all of our data from this request, stop writing it to the new request.
        req.on( 'end', function () { console.log(qs.stringify(qs.parse(postData))); newRequest.end(); });
    
    }).listen(1337);
    console.log( "Server running...");
    

    我是从黑暗面(C#)过来的,而且大多数情况下,我都在努力解决Node.js的异步问题。有了这个,我致力于在Node School和Plural Sight的教程中插入,直到我得到它!您可以提供的任何帮助将非常感激。

1 个答案:

答案 0 :(得分:0)

您想修改响应并将其转发给客户端吗?

更改newResponse处理程序以修改远程服务器的响应。

newResp.on( 'data', function ( respBody ) { resp.write( respBody ); });

newResp.on( 'data', function ( respBody ) { resp.write( MODIFY(respBody) ); });