我正在使用nodejs的mikeal'sawesomerequest模块。我还将它与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);
});

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

07-24 09:47
查看更多