vue全家桶安装axios及使用代理跨域

axios提供了一下几种请求方式

axios.request(config)
 
axios.get(url[, config])
 
axios.delete(url[, config])
 
axios.head(url[, config])
 
axios.post(url[, data[, config]])
 
axios.put(url[, data[, config]])
 
axios.patch(url[, data[, config]])
 

npm install axios --save-dev

然后在在main.js引入axios

import axios from 'axios'
Vue.prototype.$axios=axios

  // 为给定 ID 的 user 创建请求

this.$axios.get('/user?ID=12345')
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

 // 可选地,上面的请求可以这样做
this. $axios.get('/user', {
    params: {
      ID: 12345
    }
  })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

this.$axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
在config/index.js

dev: {
   // 加入以下
    proxyTable: {
      '/api': {
        target: 'http://www.xxxx.con/',//设置你调用的接口域名和端口号 别忘了加http
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/'
                //这里理解成用‘/api’代替target里面的地址,
               // 后面组件中我们掉接口时直接用api代替 比如我要调
              //  用'http://www.xxx.com/user/add',直接写‘/api/user/add’即可
        }
      }
    },

猜你喜欢

转载自blog.csdn.net/qq_36273128/article/details/81218633