好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Vue中的反向代理

Vue反向代理

config 下面的index.js文件

const ios = require('./os');

module. export s = {
  dev: {

    // Paths
    assetsS ub Directory: ' stat ic',
    assetsPublicPath: '/',
     Proxy Table: {
      '/api': {
        t arg et: 'http://192.168.0.127:8890', // 跨域地址
        changeOri gin : true, // 是否 跨域
        secure: false //是否使用https
      }
    },

    host: {ip: ios.ip,  org : 'link name.com '}, /*localhost,192.168.0.37*/
    port: 2019, // can be overwr IT ten by  PR ocess. env .PORT, if port is in use, a free one will be determined
    autoO PE n br owser: true,
    errorOverlay: true,
    notifyOnErrors: false,
    poll: false, // https://webpack.js.org/configuration/dev -s erver/ # 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 devN am e in interfaces){
  let iface = interfaces[devName];
  for(let i=0;i<iface.length;@R_ 360 _2563@){
    let alias = iface[i];
    if(alias.f ami ly  ===  ' ipv4 '  &&  alias.address ! ==  '127.0.0.1' &am p; & !alias.internal){
      IPAdress = alias.address;
    }
  }
}

module.e xp orts = { 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, 
      pat hr ewrite: {
  '^/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中的proxyTable反向代理(亲测有用) Vue项目如何设置反向代理和cookie设置问题 vue-cil之axios的二次封装与proxy反向代理使用说明 VueCli4项目配置反向代理proxy的方法步骤

总结

以上是 为你收集整理的 Vue中的反向代理 全部内容,希望文章能够帮你解决 Vue中的反向代理 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于Vue中的反向代理的详细内容...

  阅读:42次