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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

lihefei_coder   2021-11-15 我要评论
想了解Node中使用http-proxy-middleware实现代理跨域的方法步骤的相关内容吗,lihefei_coder在本文为您仔细讲解Node http-proxy-middleware代理跨域的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Node,http-proxy-middleware代理跨域,Node,代理跨域,下面大家一起来学习吧。

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}`);

});

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们