http-proxy-middleware

When the front end communicates with the background and encounters cross-domain problems, we can solve the cross-domain problem by setting up an nginx proxy to modify the source of the request. However, in fact, we can also set up a proxy ourselves through the http-proxy-middleware of nodejs.

Start the agent

1
2
3
4
5
6
7
var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use('/api', proxy({target: 'http://localhost:3001/', changeOrigin: true}));
app.listen(3000);

Start background service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//1. Import express
var express = require('express')

//2. Create express server
var server = express()

//3. access server (get or post)
//Parameter 1: Request root path
//3.1 get request
server.get('/api', function (request, response) {
// console.log(request)
Response.send ('get request successful')
})

//3.2 requests for posts
server.post('/', function (request, response) {
Response.send ('post request successful')
})

//4. Bind port
server.listen(3001)
Console.log ('Start 3001')

Using PostMan to simulate requests

Http-proxy-middleware advanced properties

Other advanced usage can refer to this blog:

https://juejin.im/post/5bd13c5ce51d457a203cebf4