【Vue】axiox基本使用

安装依赖

npm install axios

在全局配置文件main.js引入

import axios from 'axios'

// 将axios绑定到全局Vue原型上
Vue.prototype.$axios = axios

// 全局的 axios 默认值
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

使用

this.$axios.get('api',{
      params:{
        id:1
      }
    }).then(function(res){
      console.log(res)
    }).catch(function(error){
      console.log(error)
    })
this.$axios.post('api',{
      id:2,
      username:'李四'
    }).then(function(res){
      console.log(res)
    }).catch(function(error){
      console.log(error)
    })

别名方法

为方便起见,为所有支持的请求方法提供了别名

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]])

并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

相应结构:response

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 服务器响应的头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}

拦截器

  • 请求拦截器的作用比如配置header、转换数据等
  • 响应拦截器的作用比如token过期进行登录跳转等
import querystring from 'querystring'

// 在执行请求之前执行此方法
axios.interceptors.request.use(function (config) {
  // 在post提交时将data转换为json字符串
  if(config.method === "post"){
    config.data = querystring.stringify(config.data);
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 在执行axiox回调函数之前执行此方法
axios.interceptors.response.use(function (response) {
  switch (res.data.code) {
     case 401: router.push({path: '/login'});
     ......
  }
  return response;
}, function (error) {
  return Promise.reject(error);
});

跨域

配置config/index.js,proxyTable

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://localhost:8881',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    
    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    ......

在main.js中配置拦截的路径

Vue.prototype.HOST = '/api'

注意:修改配置文件后,需要 npm run dev 重启项目才能生效

使用

this.$axios.get(this.HOST + '/users',{
      params:{
        id:1
      }
    }).then(function(res){
      console.log(res)
    }).catch(function(error){
      console.log(error)
    })
发布了107 篇原创文章 · 获赞 88 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/Code_shadow/article/details/97692594