How to use HTTP-Proxy-Middleware

Create the SetupProxy.js file in the SRC directory

const proxy = require("http-proxy-middleware"); // exports = function (app) {proxy(['/mock/1241', '/mock/1105'], {target: "Http://10.118.71.83:3000/", / / the target server changeOrigin: true/false by default, whether to need to change the original host header as the goal URL, whether acting}),); }

Express combined with the HTTP-Proxy-Middleware configuration generates a reverse proxy server that proxies to http://localhost:3000 on the same domain as the request. http://localhost:3000/mock/1241/xxx is the request a proxy server, then the proxy server forwarding to http://10.118.71.83:3000/mock/1241/xxx.

Some commonly used parameters:

// Proxy middleware options var config= {target: 'http://www.example.org', // The target server that needs the proxy host ChangeOrigin: // WebSockets Pathrewrite: {'^/ API /old-path': // API /new-path // Router: / API /new-path // API /remove/path // router: / API /new-path // API /remove/path // router: / API /new-path // API /remove/path // {// If the host is requested == 'dev.localhost:3000', // Overwrite target server 'http://www.example.org' to 'host 'dev.localhost:3000' :' host '}}; Target: Used to set the target server host. ChangeOrigin: Default false, whether to change the original host header to the destination URL. WS: Sets whether WebSockets are proxied or not. Pathrewrite: Rewrite the target URL path. Router: Overrides the specified request forwarding destination

What is the difference between a forward proxy and a reverse proxy?

Forward agent: when the client want to request to the server, client will request broker to forward a proxy server, is a proxy server receives the request, will take the initiative to ask the server, the server receives the request, the response data will be returned to the forward proxy server, and finally by the forward proxy server to forward the server response data to the client. This implements client and server requests and responses.

Purpose of a forward proxy:

  • To speed up resource access, the forward proxy server can cache some hot resources. When the client requests these hot resources, the forward proxy server does not need to request the server to fetch the resources again, but only fetches the local cached resources (there may be a cache and server resources inconsistent problem).
  • Authorize client access and authenticate Internet access (whether there is still traffic or phone charges).
  • The forward proxy server can keep a record of user access (Internet behavior management) and hide user information from the outside.

Example: Internet cut off at school at night, VPN

Reverse proxy: When the client want to request to the server, the client request is actually the reverse proxy server (server cluster, you just need to expose the reverse proxy server), the reverse proxy server to receive the client’s request, through a certain strategy, request to choose the appropriate server, the server receives the request, the response data will be returned to the reverse proxy server, Finally, the reverse proxy server forwards the data of the server response to the client. In this way, the request and response of the client and the server are realized, and the real server can not be exposed in the external network environment, ensuring the security of the server.

The role of reverse proxy:

  • To ensure the security of various services in the Intranet to prevent Web attacks, large websites usually take the reverse proxy server as the public network access address, and various services are in the Intranet.
  • Load balancing, the reverse proxy server selects the appropriate service to request, to achieve traffic load balancing.
  • The reverse proxy server can restrict a portion of the traffic request service (to make the request fail) when the traffic is too large for the machine to handle.
  • Data preprocessing, processing the requested data so that the server can identify, and add or delete some data in the response data of the server, etc.

Example: Taobao shopping load balancing, gateway

Reverse proxy example for http-proxy-middleware

Start the broker

var express = require('express');
var { createProxyMiddleware } = require('http-proxy-middleware');
var app = express();
app.use('/api', createProxyMiddleware({target: 'http://localhost:3001/', changeOrigin: true}));
app.listen(3000);

Start the background service

var express = require('express') //2. Var server = express() //3. Access server (GET or POST) // parameter 1: Get ('/ API ', function (request, Server. POST ('/', function (request,)) {console.log(request) response.send('get request was successful ')}) Response) {response.send(' POST request successful ')}) //4. Listen (3001) console.log(' Start 3001')

postmanResult of request:

How does setupproxy.js work in the React project?

Before we get into the mechanics, let’s ask a question: Why is it possible to make cross-domain requests by simply creating a file called SetupProxy.js in the SRC directory? Let’s explore this with this question in mind.

Since cross-domain requests can be made after the project is started by React-Scripts Start, it is certainly possible to introduce some proxy middleware during the local service generation process and configure the middleware according to the setupproxy.js configuration. This is equivalent to creating an Express instance in an Express project and then configuring the middleware using the use method of the instance:

const app = express(); const bodyParser = require('body-parser'); // Parse the request body parameter app.use(bodyParser. Json ())

Use of HTTP-Proxy-Middleware middleware

const express = require('express'); const proxy = require('http-proxy-middleware'); var app = express(); App. Use ('/API, the proxy ({target: 'http://10.119.168.87:4000', changeOrigin: true}));

When runningreact-scripts startWhen performingscriptsIn the directorystart.jsThe script



start.jsSuch as the introduction ofconfigIn the directorypaths.jsAnd the base build scriptwebpack.config.jsanddevServerService profilewebpackDevServer.config.js



paths.jsIt holds some file pathmaps, such as our proxy configuration filesetupProxy.jsThe path of the



webpack.config.jsThis is the basic build configuration, such as style loading parsing, code compression, and so on.



webpackDevServer.config.jsThe configuration is our local service, including our cross-domain requests



After the introduction of the above documents,start.jsGenerate a local service instance (const app = express()), configures the middleware based on builds, proxy profiles, and so on, and then starts the service

In fact, local services are created using the webpack-dev-server package, which is implemented based on Express

const WebpackDevServer = require('webpack-dev-server');

const devServer = new WebpackDevServer(compiler, serverConfig);

Reference: https://www.cnblogs.com/zhaow…