Vue中的反向代理

目录Vue反向代理Vue反向代理相关概念及配置反向代理使用场景跨域的解决方案什么是反向代理反向代理原理反向代理的配置总结
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);
});

Vue反向代理相关概念及配置
反向代理使用场景 在前后端分离开发的场景,前端有个服务器(提供静态页面),后端有个服务器(提供接口)
此时,前端需要连接后端的接口,就会出现跨域问题
在发布环境中,如果存在跨域问题,使用nginx
如果前后端代码在一个服务器,不存在跨域问题

跨域的解决方案 jsonp(前端解决方案)CORS(后端解决方案):cross origin resource sharing反向代理(前端解决方案)
什么是反向代理 反向代理隐藏真实的服务端,让浏览器依然是同源

反向代理原理 通过伪造请求使得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这个名字也是自定义的
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

相关推荐

评论

展开