1. The background

In many cases, to test mock scenarios that require some kind of interface, create-React-app based production projects have the ability to build this proxy into them, providing great convenience to users.

2. Agency

Create-react-app provides two default modes associated with webpack-dev-server:

  • Easy way: Inpackage.jsonaddproxyField, specifying your mock Server address.
  • Advanced mode: insrccreatesetupProxy.jsFile, using HTTP-proxy-Middleware.

Both methods can be used without executing NPM Run eject.

2.1 Simple Mode

If my mock Server is http://localhost:4000, configure it in package.json:

{..."proxy": "http://localhost:4000". }Copy the code

The agent flow is written in react-script. The flow is as follows:

Graph LR A((request start)) --> B{Get request? } B --No--> C C --Yes--> D } D --Yes--> E D --No--> F{sockjs-node request? } F --Yes--> E F --No--> G{text/ HTML? } G --Yes--> E G --No--> C C() E()) style C stroke:#333,stroke-width:4px

Only requests under the current domain name are blocked.

2.2 Advanced Mode

The react – script in the react – scripts/config/webpackDevServer config. Judging by the following, in js will setupProxy. Js as middleware in the dev server:

if (fs.existsSync(paths.proxySetup)) {
  require(paths.proxySetup)(app);
}
Copy the code

Create the setupproxy. js file under SRC. The basic structure is as follows:

const proxy = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    "/api".// Proxy/API request
    proxy({
      target: "http://localhost:4000".logLevel: "debug".changeOrigin: true,})); };Copy the code

The last routine intercepts all/API requests. This mode can block all requests, see documentation for details.

You don’t need to install HTTP-proxy-Middleware, it’s already built into React-Script. Note that the HTTP-proxy-middleware version, which was 0.x in the example above, has changed a lot. Do not mix with the simple methods in 2.1.

3. Mock Server

For easy use, just create one using HTTP.

3.1 create a Server

You can create a mock.js file to use as the Server:

const http = require("http");
const PORT = 4000;

http
  .createServer(function ({ method, url }, res) {
    const search = new URL(url, `http://localhost:${PORT}`).searchParams;

    if (method == "POST") {
      / /...
    }

    if (method == "GET") {
      // Simulate delay
      if (search.get("t")) {
        return setTimeout(() = > res.end(), search.get("t"));
      }

      return res.end(
        JSON.stringify({
          success: true.content: "from mock",})); } }) .listen(PORT);Copy the code

3.2 Starting the Server simultaneously

Add a parallel execution to scripts in package.json:

  "scripts": {
    "start": "react-scripts start"."start:with:mock": "node mock.js & npm run start"
  },
Copy the code

Activation:

npm run start:with:mock
Copy the code

⭐ Github