vue中的跨域,多域名访问

3,694 阅读1分钟

1.vue中怎么监听路由参数的变化

   watch: {
    $route(){
      this.type= this.$route.query.type
    },
    type() {
      // console.log("重新请求" + this.type + "的数据")
      this.view();
      this.allUser = this.loadAll();
    }
  },

2.vue proxyTable配置代理,解决跨域

在文件config下的index.js中

proxyTable: {
      '/api/': {
        target: 'http://192.168.3.20:8095',
        changeOrigin: true,
        pathRewrite: {
          '^/api/': '/'
        }
      }

    },

**重要:**请求接口是加上/api!!!

axios.get('/api/schoolInfo/getInUse')
        .then(function (response) {
            console.log(1)
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        })

注意:要用代理就使用本地域名,由本地server代理请求服务器,**不能设置axios的默认请求地址,否则请求的接口会报404!!!**也可以让后端帮忙解决下跨域。

3.一个项目中请求多个域名

如果原本没有跨域问题就不需要加proxyTable代理了,如果想要请求多个域名下的接口,可以配置一个新的 axios 实例来发起第二个域名的请求,把这个新的 aixos 实例的 baseURL 配置成新的域名,就可以访问这个域名下的接口了。 使用axios.create来创建一个新的axios实例

let http = axios.create({
  baseURL: 'http://192.168.3.20:8095',
  timeout: 20000,
  headers: {
    'Content-Type': "application/json"
  },
  withCredentials: true
})
Vue.prototype.$http = http
this.$http.get('/schoolInfo/getInUse')
        .then(function (response) {
            console.log(1)
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        })