基于 promise 的 HTTP 库
用于测试请求模拟接口,RESTful 架构的 API,会根据不同的请求方法在同一个 URL 返回不同的资源。
基本使用
GET 请求
axios({method: 'get',url: 'https://jsonplaceholder.typicode.com/todos'}).then(res => {console.log(res);}).catch(err => {console.log(err);})
传入参数
- 直接在 URL 加入参数
- options 使用 params 属性
axios({method: 'get',url:'https://jsonplaceholder.typicode.com/todos?_limit=5',// 或url: 'https://jsonplaceholder.typicode.com/todos',params: {_limit: 5}}).then(res => {console.log(res);}).catch(err => {console.log(err);})
使用 axios 静态方法 get
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5').then(res => {console.log(res);}).catch(err => {console.log(err);})
POST 请求
axios({method: 'post',url: 'https://jsonplaceholder.typicode.com/todos',data: {title: 'JS++',completed: false,}}).then(res => {console.log(res);}).catch(err => {console.log(err);})
使用 axios 静态方法 post
axios.post('https://jsonplaceholder.typicode.com/todos',{title: 'JS++',completed: false,}).then(res => {console.log(res);}).catch(err => {console.log(err);})
PUT / PATCH 请求
在 RESTful 中 PUT 是整条记录全部更新(替换为新的记录),PATCH 只是更新记录中的某些 fields
axios.put('https://jsonplaceholder.typicode.com/todos/1',{title: 'JS++',completed: true,}).then(res => {console.log(res);}).catch(err => {console.log(err);})axios.patch('https://jsonplaceholder.typicode.com/todos/1',{title: 'JS++',completed: true,}).then(res => {console.log(res);}).catch(err => {console.log(err);})
DELETE 请求
axios.delete('https://jsonplaceholder.typicode.com/todos/1',).then(res => {console.log(res);}).catch(err => {console.log(err);})
批量请求
axios.all
axios.all([axios.get('https://jsonplaceholder.typicode.com/todos'),axios.get('https://jsonplaceholder.typicode.com/posts'),]).then(res=>{console.log(res[0]);console.log(res[1]);}).catch(err => {console.log(err);});
axios.spread 把结果更优雅地分开
axios.all([axios.get("https://jsonplaceholder.typicode.com/todos"),axios.get("https://jsonplaceholder.typicode.com/posts"),]).then(axios.spread((todos, posts) => {console.log(todos);console.log(posts);})).catch((err) => {console.log(err);});
请求拦截和响应拦截
axios.interceptors
axios.interceptors.request.use(config => {console.log(`${config.method.toUpperCase()} request sent to ${config.url}` at ${new Date().getTime()});}, error => {return Promise.reject(error);})
自定义请求头
可以用于配合 JWT JSON Web Tokens
const config = {header: {'Content-Type': 'application/json',.Authorization: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'}}axios.post('https://jsonplaceholder.typicode.com/todos',{title: 'JS++',completed: false,},config).then(res => {console.log(res);}).catch(err => {console.log(err);})
转换请求数据和响应数据
options.transformRequest
options.transformResponse
const options = {method: 'post',url: 'https://jsonplaceholder.typicode.com/todos',data: {title: 'Hello World',completed: false,},transformResponse: axios.defaults.transformResponse.concat(res => {const data = res.data;data.title = data.title。toUpperCase();return data;})}axios(options);
全局配置
通过修改 defaults
axios.defaults.headers.common['Authorization'] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
异常处理
axios({method: 'get',url: 'https://jsonplaceholder.typicode.com/error' // 不存在的 URL}).then(res => {console.log(res);}).catch(err => {if(err.response){console.log(err.response.data); // 服务端返回数据console.log(err.response.status); // 状态码console.log(err.response.headers); // 响应头部if(err.response.status === 404){// 响应 404 的页面} else if (err.requset){console.error(err.request); // 没有返回响应} else {console.error(err.message);}}})
取消请求
可以使用 CancelToken.source 工厂方法创建 cancel token
const source = axios.CancelToken.source();axios({method: 'get',url: 'https://jsonplaceholder.typicode.com/todos',cancelToken: source.token}).then(res => {console.log(res);}).catch(thrown => {if(axios.isCancel(thrown)){console.log('Some message:', thrown.message);}})if(true){source.cancel('Reqauest Canceled');}
axios 实例
const axiosInstance = axios.create({baseURL: 'https://jsonplaceholder.typicode.com/'})axiosInstance.get('/post').then(res => console.log(res));
config 配置
timeout 超时 单位 ms
validateStatus 验证状态码,通过就不会被 catch
{validateStatus: function(status){return status < 500}}
