Mikeal的NodeJS请求在pipe道之前修改主体

我为NodeJS使用了mikeal的真棒请求模块。 我也用express来代理API的调用,以避免旧版浏览器的CORS问题:

app.use(function(request, response, next) { var matches = request.url.match(/^\/API_ENDPOINT\/(.*)/), method = request.method.toLowerCase(), url; if (matches) { url = 'http://myapi.com' + matches[0]; return request.pipe(req[method](url)).pipe(response); } else { next(); } }); 

有没有一种方法,我可以修改身体,然后再将request的响应传回来express

基于这个答案: 在node.js中输出之前更改响应主体我做了一个工作的例子,我用我自己的应用程序:

 app.get("/example", function (req, resp) { var write = concat(function(response) { // Here you can modify the body // As an example I am replacing . with spaces if (response != undefined) { response = response.toString().replace(/\./g, " "); } resp.end(response); }); request.get(requestUrl) .on('response', function (response) { //Here you can modify the headers resp.writeHead(response.statusCode, response.headers); } ).pipe(write); }); 

任何改进将受到欢迎,希望它有帮助!

您可能想要使用转换stream 。 一些谷歌search后,我发现了以下博客文章 。