axios 是一个功能强大且易于使用的 HTTP 客户端库,提供了丰富的功能和配置选项。以下是 axios 的完整使用示例:
发送 GET 请求:
axios.get('https://jsonplaceholder.typicode.com/posts').then(response => {console.log(response.data);}).catch(error => {console.error(error);});
发送 POST 请求:
axios.post('https://jsonplaceholder.typicode.com/posts', {title: 'foo',body: 'bar',userId: 1}).then(response => {console.log(response.data);}).catch(error => {console.error(error);});
设置请求头:
axios.get('https://jsonplaceholder.typicode.com/posts', {headers: {'Authorization': 'Bearer token'}}).then(response => {console.log(response.data);}).catch(error => {console.error(error);});
并发请求:
axios.all([axios.get('https://jsonplaceholder.typicode.com/posts/1'),axios.get('https://jsonplaceholder.typicode.com/posts/2')]).then(axios.spread((response1, response2) => {console.log(response1.data);console.log(response2.data);})).catch(error => {console.error(error);});
取消请求:
const source = axios.CancelToken.source();axios.get('https://jsonplaceholder.typicode.com/posts', {cancelToken: source.token
}).then(response => {console.log(response.data);}).catch(error => {if (axios.isCancel(error)) {console.log('Request canceled:', error.message);} else {console.error(error);}});// 取消请求
source.cancel('Request canceled by the user');
设置默认配置:
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.headers.post['Content-Type'] = 'application/json';
以上是 axios 的一些常用用法和功能示例