likes
comments
collection
share

使用 http-proxy 实现 SAP UI5 请求的代理重定向

作者站长头像
站长
· 阅读数 24

http-proxy 是一个有用的代理工具库,适用于 HTTP 请求的代理和重定向。

创建代理服务器的方法:

var httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer(options);

options 为代理服务器创建参数。

一些例子:创建代理服务器,监听在 8000 端口上,收到请求后,会转发给 端口 9000 的服务器上。

var http = require('http'),
    httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)

端口 9000 的服务器,只是简单地发送一个请求代理成功的提示信息。

//
// Create your target server
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

看个具体的例子。

我在一个 SAP UI5 应用的 manifest.json 文件里,定义了一个 dataSources,名叫 invoiceRemote,uri 为:

http://localhost:8082/https:/...

使用 http-proxy 实现 SAP UI5 请求的代理重定向

这样,该 SAP UI5 应用,会发送一个 url,到 localhost 8082 去请求元数据。

因此,我需要有一个自己的服务器,监听在端口 8082 上:

var http = require('http'),
    httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8082); 

并且通过 target:'http://localhost:9000' 的服务器构造函数参数,指定当监听在端口 8082 的服务器接收到 HTTP 请求后,自动转发到监听在 9000 端口的服务器上。

使用 http-proxy 实现 SAP UI5 请求的代理重定向

在端口 9000 上监听的服务器,收到请求后只是简单的发送 request successfully proxied 的响应:

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

测试:在浏览器里输入如下 url:

http://localhost:8082/https:/...

使用 http-proxy 实现 SAP UI5 请求的代理重定向

该请求依次经历了下列的处理逻辑:

  1. 请求被代理服务器 8082 成功拦截;
  2. 请求被代理服务器 8082 转发到服务器 9000;
  3. 请求在服务器 9000 被处理,请求明细被序列化成 JSON 字符串,作为输出发送给 HTTP 请求的响应结构。

更多Jerry的原创文章,尽在:"汪子熙":使用 http-proxy 实现 SAP UI5 请求的代理重定向