脚本宝典收集整理的这篇文章主要介绍了Vue中的反向代理,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
config下面的index.js文件
const ios = require('./os'); module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', ProxyTable: { '/api': { target: 'http://192.168.0.127:8890', // 跨域地址 changeOrigin: true, //是否跨域 secure: false //是否使用https } }, host: {ip: ios.ip, org: 'linkname.com'}, /*localhost,192.168.0.37*/ port: 2019, // can be overwrITten by PRocess.env.PORT, if port is in use, a free one will be determined autoOPEnbrowser: true, errorOverlay: true, notifyOnErrors: false, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader? useEslint: false, // If true, eslint errors and warnings will also be shown in the error overlay // in the browser. showEslintErrorsInOverlay: false, devtool: '#cheap-source-map', //‘inline-source-map' cacheBusting: true, cssSourceMap: false, } }
ios 文件
const interfaces = require('os').networkInterfaces(); let IPAdress = ''; for(let devName in interfaces){ let iface = interfaces[devName]; for(let i=0;i<iface.length;i++){ let alias = iface[i]; if(alias.family === 'ipv4' && alias.address !== '127.0.0.1' && !alias.internal){ IPAdress = alias.address; } } } module.exports = { ip : IPAdress }
API请求
// 导入axios import axios From 'axios' axios.get('/api/v1/home/getIndexInfo').then(function(res){ console.LOG(res); });
在前后端分离开发的场景,前端有个服务器(提供静态页面),后端有个服务器(提供接口)
此时,前端需要连接后端的接口,就会出现跨域问题
在发布环境中,如果存在跨域问题,使用nginx
如果前后端代码在一个服务器,不存在跨域问题
反向代理隐藏真实的服务端,让浏览器依然是同源
通过伪造请求使得http请求为同源的,然后将同源的请求发送到反向代理服务器上,由反向代理服务器去请求真正的url,这样就绕过直接请求真正的url导致的跨域问题
vue-cli3的反向代理
在项目根目录下新建vue.config.js文件
配置代码:
module.exports = { lintOnSave:false, devServer:{ proxy: { '/api': { target: 'http://localhost:80', changeOrigin: true, pathrewrite: { '^/api': "" }, '/apidouban': { target: 'http://localhost:3001', changeOrigin: true, pathRewrite: { '^/apidouban': "" } } } } }
反向代理执行过程:
axios访问地址中的 /api 转换为 target + /api:
(eg:http:localhost:9000/api/goods 转换为 http://localhost:80/api/goods)
创建虚拟服务器
去掉/api:
(eg:http://localhost:80/goods)
页面axios请求时请求与页面url一样的地址,地址后面拼接api,反向代理服务器会将请求地址中/api之前的地址转变为target中的地址,这样一来在页面发生请求时浏览器会认为是同源,不会报错;
有时候一个页面服务器可能会请求好几个后端服务器,这时,反向代理可以设置多个,/api这个名字也是自定义的
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本宝典。
以上是脚本宝典为你收集整理的Vue中的反向代理全部内容,希望文章能够帮你解决Vue中的反向代理所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。