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

举报
Jerry Wang 发表于 2022/10/03 10:27:24 2022/10/03
【摘要】 http-proxy 是一个有用的代理工具库,适用于 HTTP 请求的代理和重定向。创建代理服务器的方法:var httpProxy = require('http-proxy');var proxy = httpProxy.createProxyServer(options);options 为代理服务器创建参数。一些例子:创建代理服务器,监听在 8000 端口上,收到请求后,会转发给 端...

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://services.odata.org/V2/Northwind/Northwind.svc/

这样,该 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://services.odata.org/V2/Northwind/Northwind.svc/

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

  1. 请求被代理服务器 8082 成功拦截;
  2. 请求被代理服务器 8082 转发到服务器 9000;
  3. 请求在服务器 9000 被处理,请求明细被序列化成 JSON 字符串,作为输出发送给 HTTP 请求的响应结构。
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。