【问题标题】:Nuxt: modify a response from a proxied server using NuxtJS server middlewareNuxt:使用 NuxtJS 服务器中间件修改来自代理服务器的响应
【发布时间】:2019-11-18 14:45:42
【问题描述】:

我使用NuxtJS server middleware 作为代理通行证,如this article 中所述 将传入请求代理到内部服务以避免跨域问题。

const httpProxy = require('http-proxy')
const proxy = httpProxy.createProxyServer()
const API_URL = 'https://api.mydomain.com'

export default function(req, res, next) {
  proxy.web(req, res, {
    target: API_URL
  })
}

如何分析代理服务器的响应并在此级别修改它?

【问题讨论】:

    标签: http server proxy middleware nuxt.js


    【解决方案1】:

    我在http-proxy documentation 中找到了一个示例。 要修改响应,selfHandleResponse 必须设置为 true。 这是文档中的示例:

    var option = {
      target: target,
      selfHandleResponse : true
    };
    proxy.on('proxyRes', function (proxyRes, req, res) {
        var body = [];
        proxyRes.on('data', function (chunk) {
            body.push(chunk);
        });
        proxyRes.on('end', function () {
            body = Buffer.concat(body).toString();
            console.log("res from proxied server:", body);
            res.end("my response to cli");
        });
    });
    proxy.web(req, res, option);
    

    如果请求与某个 url 匹配,下面的代码允许我处理代理答案,否则只转发(管道)它。

    proxy.once('proxyRes', function(proxyRes, req, res) {
      if (!req.originalUrl.includes('api/endpoint')) {
        res.writeHead(proxyRes.statusCode) // had to reset header, otherwise always replied proxied answer with HTTP 200
        proxyRes.pipe(res)
      } else {
        // modify response
        let body = []
        proxyRes.on('data', function(chunk) {
          body.push(chunk)
        })
        proxyRes.on('end', function() {
          body = Buffer.concat(body).toString()
          console.log('res from proxied server:', body)
          res.end('my response to cli')
        })
      }
    })
    

    请注意,我添加了将 .on() 替换为 once() 以使其正常工作。

    【讨论】:

      猜你喜欢
      • 2015-10-09
      • 1970-01-01
      • 2023-03-17
      • 2011-01-26
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 2023-04-11
      相关资源
      最近更新 更多