美文网首页
VUE配置跨域

VUE配置跨域

作者: 小碗吃不了 | 来源:发表于2019-12-23 17:04 被阅读0次

    开发环境

    • 根目录下config文件夹下的index.js

    • /api是为了统一配置跨域而在接口的开头加上标识(依据个人习惯)

    • 为防止接口未统一设置需在前端手动预添加,可在重写借口处再配置

    • 基本用法

       proxyTable: {
        '/api':{
           target: 'http://10.1.63.26:19080/',  // 接口域名
           changeOrigin: true,  //是否跨域
           pathRewrite: {
               '^/api': '/api'   //根据实际情况设置是否需要重写接口(置空、不变、重置)
           }
        }
      }
      
      例:'http://localhost:8080/api/findManual' ===> 'http://10.1.63.26:19080/api/findManual'
      
      若后台接口没有统一设置,在前端接口配置时手动加上/api
      如:接口为'http://10.1.63.26:19080/findManual/',
          配置成 let someApi = 'api' + '/findManual'
          在重写接口处置空  '^/api': ' '  
      
    • 需重写接口情况

      proxyTable: {
        '/api': {
          target: 'http://www.ykt.com/',//接口域名
          changeOrigin: true,//是否跨域
          pathRewrite: {
              '^/api': '/index/index'//需要rewrite重写
          }
        }
      }
      
      例:'localhost:8080/api/getbuildcate'   ===>  'www.ykt.com/index/index/getbuildcate'
      

    生产环境

    • 统一接口配置文件中设置baseURL在axios中

       //判断是否是生产环境
       //process.env.NODE_ENV用于区分是生产环境还是开发环境
       //在根目录config文件下dev.env.js和prod.env.js查看
       var isPro = process.env.NODE_ENV === 'production' 
      //根据环境不同导出不同的baseURL
       let baseURL =  isPro ? 'http://www.ykt.com/' : '/api'
      

    • axios中baseURL设置

      假设你vue-cli起了一个开发环境,地址为http://localhost:8080
      //例1 当不设置baseURL时
      axios.get('/user')  //访问/user相当于访问 http://localhost:8080/user
      
      //例2 
      axios.defaults.baseURL='/apis'
      axios.get('/user')  //访问/user就相当于访问 http://localhost:8080/apis/user
      
      //例3
      axios.defaults.baseURL='https://sbsb.com'
      axios.get('/user')  //访问/user就相当于访问 https://sbsb.com/user
      
      //例4
      axios.defaults.baseURL='https://sbsb.com/apis'
      axios.get('/user')  //访问/user就相当于访问 https://sbsb.com/apis/user
      

    参考一
    参考二

    相关文章

      网友评论

          本文标题:VUE配置跨域

          本文链接:https://www.haomeiwen.com/subject/goecnctx.html