目录
- 1.安装代理模块
- 2.配置代理
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}`); });
到此这篇关于Node中使用http-proxy-middleware实现代理跨域的方法步骤的文章就介绍到这了,更多相关Node http-proxy-middleware代理跨域内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!