Nuxt:使用NuxtJS服务器中间件修改来自代理服务器的响应

问题描述 投票:0回答:1

我正在使用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
1个回答
0
投票

我在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()以使其正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.