Article From:https://www.cnblogs.com/zhaoweikai/p/9969282.html

This paper mainly talks about the usage and implementation principle of http-proxy-middleware.

Introduction

http-proxy-middlewareUsed to forward requests to other servers in the background.

For example, our current host A is http://localhost:3000/. Now the browser sends a request, request interface/api, and the data of this request is on another server B (http://10.119.168.87:4000).At this time, the request can be sent directly to the B host by setting up a proxy on the A host.

The simple implementation code is as follows:

1 var express = require('express');
2 var proxy = require('http-proxy-middleware');
3 
4 var app = express();
5 
6 app.use('/api', proxy({target: 'http://10.119.168.87:4000', changeOrigin: true}));
7 app.listen(3000);

Explanation: We started a small server on port 3000 with express and used it.app.use('/api', proxy({target: 'http://10.119.168.87:4000/', changeOrigin: true}))In this sentence, the / API request sent to port 3000 is forwarded to port 4000. Instant requesthttp://localhost:3000/apiEquivalent to request http://10.119.168.87:4000/api

Two installation

1 $ npm install --save-dev http-proxy-middleware

Triple Use and Interface Description

proxy([context,] config)

1 var proxy = require('http-proxy-middleware');
2 
3 var apiProxy = proxy('/api', {target: 'http://www.example.org'});
4 //                   \____/   \_____________________________/
5 //                     |                    |
6 //                Request target server to be forwarded

Note: The first parameter can be omitted.

The following example is a server usage built with Express:

 1 // Citation dependency
 2 var express = require('express');
 3 var proxy = require('http-proxy-middleware');
 4 
 5 // proxy Middleware options
 6 var options = {
 7         target: 'http://www.example.org', // Target server host
 8         changeOrigin: true,               // Default false, do you need to change the original host header to the target URL
 9         ws: true,                         // Whether to proxy WebSockets
10         pathRewrite: {
11             '^/api/old-path' : '/api/new-path',     // Rewrite requests, such as API / old-path that our source accesses, and the request is resolved to / API / new-path
12             '^/api/remove/path' : '/path'           // Ditto
13         },
14         router: {
15             // If the request host=='dev.localhost:3000',
16             // Rewrite the target server'http://www.example.org'to'http://localhost:8000'
17             'dev.localhost:3000' : 'http://localhost:8000'
18         }
19     };
20 
21 // Create agent
22 var exampleProxy = proxy(options);
23 
24 // Use agent
25 var app = express();
26     app.use('/api', exampleProxy);
27     app.listen(3000);

3.1 Parameter one[context]Detailed explanation

Below is a complete address partition:

foo://example.com:8042/over/there?name=ferret#nose
 \_/  \______________/\_________/ \_________/ \__/
  |           |            |            |       |
Protocol Host Path Query Fragments

The first parameter mainly sets the path to be proxyed. The parameter has the following usage:

1)It can be omitted.

  • proxy({...}):Match any path and all requests will be forwarded.

2)You can set it to a path string

  • proxy('/', {...}) :Match any path and all requests will be forwarded.
  • proxy('/api', {...}):Match / API start request

3)You can set it as an array

  • proxy(['/api', '/ajax', '/someotherpath'], {...}) :Matching multiple paths

4)You can set it as a function (custom configuration rules)

1 /**
2  * @return {Boolean}
3  */
4 var filter = function (pathname, req) {
5     return (pathname.match('^/api') && req.method === 'GET');
6 };
7 
8 var apiProxy = proxy(filter, {target: 'http://www.example.org'})

5)Can be set to wildcards

Fine-grained matching can use wildcard matching, the Glob matching pattern is created by micromatch, and access micromatch or glob to find more use cases.

  • proxy('**', {...}) Match any path and all requests will be forwarded.
  • proxy('**/*.html', {...}) Match any request ending with. html;
  • proxy('/*.html', {...}) Matching requests ending in HTML in the current path;
  • proxy('/api/**/*.html', {...}) Matching / API requests ending with html;
  • proxy(['/api/**', '/ajax/**'], {...}) combination
  • proxy(['/api/**', '!**/bad.json'], {...}) Barring**/bad.json

3.2 Detailed explanation of parameter 2 config

The interface is an object with the following parameters:
 1 // proxy Middleware options
 2 var config= {
 3         target: 'http://www.example.org', // Target server host
 4         changeOrigin: true,               // Default false, do you need to change the original host header to the target URL
 5         ws: true,                         // Whether to proxy WebSockets
 6         pathRewrite: {
 7             '^/api/old-path' : '/api/new-path',     // Rewrite requests, such as API / old-path that our source accesses, and the request is resolved to / API / new-path
 8             '^/api/remove/path' : '/path'           // Ditto
 9         },
10         router: {
11             // If the request host=='dev.localhost:3000',
12             // Rewrite the target server'http://www.example.org'to'http://localhost:8000'
13             'dev.localhost:3000' : 'http://localhost:8000'
14         }
15     };
16 
17 // Create agent
18 var exampleProxy = proxy(config);

1)target

Used to set the target server host.

2)changeOrigin

By default false, do you need to change the original host header to the target URL?

3)ws

Set whether to proxy websockets.

4)pathRewrite

 Rewrite the target URL path.
 1 // Rewrite
 2 pathRewrite: {'^/old/api' : '/new/api'}
 3 
 4 // remove
 5 pathRewrite: {'^/remove/api' : ''}
 6 
 7 // Add to
 8 pathRewrite: {'^/' : '/basepath/'}
 9 
10 // custom
11 pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }

5)router

Rewrite the specified request forwarding target.

 1 // Use the host or path to match and return the first match to the result
 2 // So the order of configuration is important.
 3 router: {
 4     'integration.localhost:3000' : 'http://localhost:8001',  // host only
 5     'staging.localhost:3000'     : 'http://localhost:8002',  // host only
 6     'localhost:3000/api'         : 'http://localhost:8003',  // host + path
 7     '/rest'                      : 'http://localhost:8004'   // path only
 8 }
 9 
10 // custom
11 router: function(req) {
12     return 'http://localhost:8004';
13 }

3.3 Event

http-proxy-middlewareSome requests for listening events are also provided.

  • option.onError:
1 // Monitor the onerr event of proxy
2 proxy.on('error', function (err, req, res) {
3   res.writeHead(500, {
4     'Content-Type': 'text/plain'
5   });
6 
7   res.end('Something went wrong. And we are reporting a custom error message.');
8 });
  • option.onProxyRes:Listen for proxy response events
1 proxy.on('proxyRes', function (proxyRes, req, res) {
2   console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
3 });
  • option.onProxyReq:Listen for proxy request events
1 proxy.on('proxyReq', function onProxyReq(proxyReq, req, res) {
2     proxyReq.setHeader('x-added', 'foobar');
3 });
  • option.onProxyReqWs:
1 function onProxyReqWs(proxyReq, req, socket, options, head) {
2     proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
3 }
  • option.onOpen:Listening for information from the target server
1 proxy.on('open', function (proxySocket) {
2   proxySocket.on('data', hybiParseAndLogMessage);
3 });
  • option.onClose:Show web socket link separation
1 proxy.on('close', function (res, socket, head) {
2   console.log('Client disconnected');
3 });

Fourth Realization Principle and Source Code Interpretation

 http-proxy-middlewareActually, it uses http-proxy library to realize the function of proxy middleware.

1)proxy([context,] config),This step is to execute the HttpProxyMiddleware method in the source code. The core content of this method is to call the httpProxy. createProxyServer () method to create a proxy service and return a middlew at the end of the method.Are.

httpProxyOfficial website: https://github.com/nodejitsu/node-http-proxy#core-concept

2)Analytical return value middleware is a function whose core is to use the return value of the proxy service created above to invoke the web method for forwarding requests.

3)app.use(‘/api’, proxy(options)),When the local server listens to the’/ api’interface of client requests, it returns to the upper middleware function, from which it can be seen that the request is forwarded to the proxy server.

Summary: http-proxy-middleware actually encapsulates http-proxy, which is more convenient and simple to use.

 

Reference & amp; Content Source

Official website: https://github.com/chimurai/http-proxy-middleware

Brief book: https://www.jianshu.com/p/a248b146c55a

 

Leave a Reply

Your email address will not be published. Required fields are marked *