关于http:使用-httpproxy-实现-SAP-UI5-请求的代理重定向

8次阅读

共计 1522 个字符,预计需要花费 4 分钟才能阅读完成。

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

该申请顺次经验了下列的解决逻辑:

  1. 申请被代理服务器 8082 胜利拦挡;
  2. 申请被代理服务器 8082 转发到服务器 9000;
  3. 申请在服务器 9000 被解决,申请明细被序列化成 JSON 字符串,作为输入发送给 HTTP 申请的响应构造。

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

正文完
 0