当前位置:主页 > 脚本语言 > NodeJS >

Node中使用http-proxy-middleware实现代理跨域的方法步骤

时间:2022-03-03 09:47:13 | 栏目:NodeJS | 点击:

1.安装代理模块

cnpm i http-proxy-middleware -S

2.配置代理

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

/* 代理配置 start */
const proxy = require('http-proxy-middleware'); //引入代理模块
const proxyOptions = {
    target: 'http://127.0.0.1:9999', //后端服务器地址
    changeOrigin: true //处理跨域
};
const exampleProxy = proxy('/api/*', proxyOptions); //api前缀的请求都走代理
app.use(exampleProxy);
/* 代理配置 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">请求服务器接口1</button>
         <button id="btn2">请求服务器接口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(`服务器运行在http://${hostName}:${port}`);

});

您可能感兴趣的文章:

相关文章