axios (Cheat Sheet)

141 阅读2分钟

axios

本篇参考以下两篇文档

axios 作弊表

axios 中文文档

执行 GET 请求

// 为给定 ID 的 user 创建请求 
axios.get('/user?ID=12345')   
  .then(function (response) {     
    console.log(response);  
  })   
  .catch(function (error) {     
    console.log(error);   
  });  
      
// 上面的请求也可以这样做 
axios.get('/user', {     
  params: {       
    ID: 12345     
  }   
})   
  .then(function (response) {     
    console.log(response);   
  })   
  .catch(function (error) {     
    console.log(error);   
  });
axios({
  method: 'get', 
  url: 'http://bit.ly/2mTM3nY', 
  responseType: 'stream'
}) 
  .then(function(response) { 
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 
  });

POST 请求

axios.post('/user', {    
  firstName: 'Fred',     
  lastName: 'Flintstone'   
  })   
  .then(function (response) {     
    console.log(response);   
  })   
  .catch(function (error) {     
    console.log(error);   
  });
  // 发送Post请求
axios({ 
  method: 'post', 
  url: '/user/12345', 
  data: { 
    firstName: 'Fred', 
    lastName: 'Flintstone' 
  } 
});

执行多个并发请求

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) { 
  // 两个请求现在都执行完成
  }));

创建实例

  • 可以使用自定义配置新建一个axios实例
var instance = axios.create({ 
 baseURL: 'https://some-domain.com/api/', 
 timeout: 1000, 
 headers: {'X-Custom-Header': 'foobar'} 
});

Response

axios.get('/user/12345') 
      .then(function(response) { 
        console.log(response.data); 
        console.log(response.status); 
        console.log(response.statusText); 
        console.log(response.headers); 
        console.log(response.config); });

config

// 全局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'; 

// 自定义实例默认值 

// 创建实例时设置默认配置
var instance = axios.create({ 
  baseURL: 'https://api.example.com' 
}); 

// 创建实例后更改默认值 
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 

// 配置优先级顺序

// 使用库提供的配置默认值创建实例
// 此时,超时配置值为“0” 这是库的默认值
var instance = axios.create(); 

// 覆盖库的超时默认值
// 现在,所有请求都将在超时之前等待 2.5 秒
instance.defaults.timeout = 2500; 

// 覆盖此请求的超时,因为已知需要很长时间
instance.get('/longRequest', { 
      timeout: 5000 
    });

拦截器

// 拦截请求/响应

// 添加请求拦截器
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); 
}); 
// 移除拦截器

var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); 

// 自定义实例拦截器

var instance = axios.create(); 
instance.interceptors.request.use(function () {/*...*/});

错误处理

// 捕获错误
axios.get('/user/12345') 
  .catch(function (error) { 
    if (error.response) { 
    // 请求已发出,服务器使用状态代码进行响应
    // 超出了2xx的范围
    console.log(error.response.data); 
    console.log(error.response.status); 
    console.log(error.response.headers); 
  } else if (error.request) { 
    // 请求响应,但未收到任何回复
    // `error.request` 是浏览器中XMLHttpRequest的一个例子且是个实例
    // http.ClientRequest in node.js 
    console.log(error.request); 
  } else { 
    // 设置触发错误的请求时发生的情况
    console.log('Error', error.message); 
  } 
    console.log(error.config); 
  }); 
  
// 自定义HTTP状态码错误

axios.get('/user/12345', { 
  validateStatus: function (status) { 
    return status < 500; // 仅当状态代码大于或等于 500 时才Reject
  } 
})

取消请求

// 取消请求和token 

var CancelToken = axios.CancelToken; 
var source = CancelToken.source(); 

axios.get('/user/12345', { 
  cancelToken: source.token 
}).catch(function(thrown) { 
  if (axios.isCancel(thrown)) { 
    console.log('Request canceled', thrown.message); 
  } else { 
  // handle error
  } 
}); 
axios.post('/user/12345', { 
  name: 'new name' 
}, { 
  cancelToken: source.token 
}) 

// 取消请求(消息参数是可选的)
source.cancel('Operation canceled by the user.'); 

// 构建取消Token

var CancelToken = axios.CancelToken; 
var cancel; 

axios.get('/user/12345', { 
  cancelToken: new CancelToken(function executor(c) { 
    // 执行器函数接收一个取消函数作为参数
    cancel = c; 
  }) 
}); 

// 取消请求
cancel();