如何使用vue axios?

一、安装axios

$ npm install axios

二、引入axios

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

三、发送请求

//get请求
axios.get('/user', {
    
    
  params: {
    
    
    ID: 12345
  }
})
.then(function (response) {
    
    
  console.log(response);
})
.catch(function (error) {
    
    
  console.log(error);
});

//post请求
axios.post('/user', {
    
    
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
    
    
  console.log(response);
})
.catch(function (error) {
    
    
  console.log(error);
});

四、使用拦截器

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    
    
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    
    
    // 对响应数据做点什么
    return response;
  }, function (error) {
    
    
    // 对响应错误做点什么
    return Promise.reject(error);
  });

五、全局的 axios 默认值

axios.defaults.baseURL = 'https://api.example.com';  //设置默认请求地址
axios.defaults.headers.common['token'] = 'token';  //对header设置默认token
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

;

猜你喜欢

转载自blog.csdn.net/pgzero/article/details/114220853