vue axios的使用以及解决跨域问题

安装axios(前提是已经安装了vue)

npm install axios --save

使用axios

1. 先在main.js中调用

import axios from 'axios'

axios.defaults.baseURL = "http://www.xxx.com";
Vue.prototype.$http = axios;

2. 在Vue实例中使用

this.$http
  .post('/demo/xxx/xxx', {
    data: data
  })
  .then(function(res) {
    console.log(res.data)
  })
  .catch(function() {
    console.log("error");
  });

但是呢,可能会遇上跨域问题

解决方法如下:

1. 修改main.js的代码

// axios.defaults.baseURL = 'http://www.xxx.com'
axios.defaults.baseURL = '/api'

2. 在config/index.js文件中的proxyTable添加以下代码

'/api':{
  target: "http://www.xxx.com",
  changeOrigin:true,
  pathRewrite:{
      '^/api':''
  }
}

原理:

因为我们给url加上了前缀/api,我们访问/demo/xxx/xxx就当于访问了:localhost:8080/demo/xxx/xxx(其中localhost:8080是默认的IP和端口)

在index.js中的proxyTable中拦截了/api,并把/api及其前面的所有替换成了target中的内容,因此实际访问url是http://www.xxx.com/demo/xxx/xxx

如有错误之处,请指出,互相学习。

猜你喜欢

转载自blog.csdn.net/mossbaoo/article/details/84070660