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

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

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:/...

这样,该 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 端口的服务器上。

在端口 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:/...

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

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

更多Jerry的原创文章,尽在:"汪子熙":

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

javascript前端htmlhtml5sap

扩展阅读

加个好友,技术交流

1628738909466805.jpg