Method Steps of Using http proxy middleware to Realize Proxy Cross domain in Node

  • 2021-12-05 05:23:22
  • OfStack

Directory 1. Install the agent module 2. Configure the agent

1. Install the agent module


cnpm i http-proxy-middleware -S

2. Configure the agent


const express = require('express');
const app = express();

/*  Agent configuration  start */
const proxy = require('http-proxy-middleware'); // Introducing agent module 
const proxyOptions = {
    target: 'http://127.0.0.1:9999', // Back-end server address 
    changeOrigin: true // Handling cross-domain 
};
const exampleProxy = proxy('/api/*', proxyOptions); //api Prefix requests all go proxy 
app.use(exampleProxy);
/*  Agent configuration  end */

const hostName = '127.0.0.1';
const port = 8080;

app.get('/', function(req, res) {

    
    const html =
    `<!DOCTYPE html>
 <html lang="en">
     <head>
         <meta charset="UTF-8" />
         <meta name="viewport" content="width=device-width, initial-scale=1.0" />
         <meta http-equiv="X-UA-Compatible" content="ie=edge" />
         <title>Document</title>
     </head>
     <body>
         <button id="btn1"> Request server interface 1</button>
         <button id="btn2"> Request server interface 2</button>
         <script src="https://cdn.bootcss.com/axios/0.19.0/axios.min.js"></script>
         <script>
             document.getElementById('btn1').addEventListener(
                 'click',
                 () => {
                     axios.get('/api/hello', {
                         params: {
                             key: 'hello'
                         }
                     });
                 },
                 false
             );
 
             document.getElementById('btn2').addEventListener(
                 'click',
                 () => {
                     axios.get('/api/word', {
                         params: {
                             key: 'word'
                         }
                     });
                 },
                 false
             );
         </script>
     </body>
 </html>`;

    res.setHeader('Content-Type', 'text/html');
    res.send(html);
});


app.listen(port, hostName, function() {

    console.log(` The server runs in the http://${hostName}:${port}`);

});

Related articles: