脚本宝典收集整理的这篇文章主要介绍了Node中使用http-proxy-middleware实现代理跨域的方法步骤,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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代理跨域内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!
以上是脚本宝典为你收集整理的Node中使用http-proxy-middleware实现代理跨域的方法步骤全部内容,希望文章能够帮你解决Node中使用http-proxy-middleware实现代理跨域的方法步骤所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。