node.js - Mikeal 的 NodeJS 请求在管道之前修改主体

标签 node.js express request

我正在使用 mikeal's太棒了request NodeJS 模块。我也将它与 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 之前,有没有办法修改正文?

最佳答案

基于这个答案:Change response body before outputting in 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);
});

欢迎任何改进,希望对您有所帮助!

关于node.js - Mikeal 的 NodeJS 请求在管道之前修改主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18141499/

相关文章:

node.js - 从 C# 调用 Edge.js 时,如何 Hook stdout 和 stderr?

javascript (node.js) 将 url hash 转换为带参数的 url

asp.net - 为什么我的 ASP Page.Request.Files[] 总是空的?我已经尝试了所有发布的修复程序

Node.js Typescript 包含内容

javascript - Node 记录未捕获的异常(Winston V3)

node.js - 如何查找 Node.js UnhandledPromiseRejectionWarning 中哪些 Promise 未处理?

javascript - 在 Node.js 中加载客户端 Javascript 和 CSS

javascript - Mongoose 错误填充虚拟

node.js - 无法在 for 循环中传递项目以将两个项目一起打印

node.js - 如何一个接一个地运行相同的 promise NodeJs