index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous" />
<title>Axios全方位解析+运用</title>
</head>
<body>
<div class="container my-5">
<div class="text-center">
<h1 class="display-4 text-center mb-3">Axios全方位运用</h1>
<button class="btn btn-primary my-3" id="get">GET</button>
<button class="btn btn-info" id="post">POST</button>
<button class="btn btn-warning" id="update">PUT/PATCH</button>
<button class="btn btn-danger" id="delete">DELETE</button>
<button class="btn btn-secondary" id="sim">批量请求</button>
<button class="btn btn-secondary" id="headers">请求头</button>
<button class="btn btn-secondary" id="transform">Transform</button>
<button class="btn btn-secondary" id="error">Error处理</button>
<button class="btn btn-secondary" id="cancel">取消请求</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="start.js"></script>
</body>
</html>
start.js
function getTodos() {
axios('http://jsonplaceholder.typicode.com/todos?_limit=5', {
timeout: 5000
})
.then(res => { console.log('get', res) })
.catch(err => console.log(err))
}
function addTodos() {
axios.post('http://jsonplaceholder.typicode.com/todos', {
title: 'post测试',
complete: false
})
.then(res => console.log('post', res))
.catch(err => console.log(err))
}
function updateTodo() {
axios.patch('http://jsonplaceholder.typicode.com/todos/1', {
title: 'patch测试',
complete: true
})
.then(res => console.log('patch', res))
.catch(err => console.log(err))
}
function removeTodo() {
axios.delete('http://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log('delete', res))
.catch(err => console.log(err))
}
function getData() {
axios.all([
axios.get('http://jsonplaceholder.typicode.com/todos?_limit=5'),
axios.get('http://jsonplaceholder.typicode.com/posts?_limit=5'),
])
.then(axios.spread((todos, posts) => console.log('批量[1]', posts)))
.catch(err => console.log(err))
}
function customHeaders() {
const config = {
headers: {
"Content-Type": "application/json",
Authorization: 'sometoken0002'
}
}
axios.post('http://jsonplaceholder.typicode.com/todos', {
title: '自定义请求头测试',
complete: true
}, config)
.then(res => console.log('自定义请求头', res))
.catch(err => console.log(err))
}
function transformResponse() {
const options = {
method: 'post',
url: "http://jsonplaceholder.typicode.com/todos",
data: { title: 'hello world' },
transformResponse: axios.defaults.transformResponse.concat(data => {
data.title = data.title.toUpperCase();
return data
})
}
axios(options).then(res => console.log('对请求头的title值进行转换', res))
}
function errorHandle() {
axios('http://jsonplaceholder.typicode.com/todoss')
.then(res => { console.log('error', res) })
.catch(err => {
if (err.response) {
const { data, status, headers } = err.response
console.log('err处理 data, status, headers', data, status, headers)
if (status == 404) {
alert('客户端请求出现问题!')
} else if (status >= 500) {
alert('服务端接口出现问题!')
}
} else if (err.request) {
console.log(err.request)
} else {
console.log(err.message)
}
})
}
function cancelToken() {
const source = axios.CancelToken.source();
axios('http://jsonplaceholder.typicode.com/todos', {
cancelToken: source.token
})
.then(res => { console.log('get', res) })
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('request canceled', thrown.message)
}
})
if (true) {
source.cancel('请求取消')
}
}
axios.interceptors.request.use(
config => {
console.log(`${config.method.toUpperCase()} 请求地址:${config.url} at ${new Date().getTime()}`);
return config;
},
error => {
return Promise.reject(error)
}
)
const axiosInstance = axios.create({
baseURL: 'http://jsonplaceholder.typicode.com'
});
document.getElementById('get').addEventListener('click', getTodos);
document.getElementById('post').addEventListener('click', addTodos);
document.getElementById('update').addEventListener('click', updateTodo);
document.getElementById('delete').addEventListener('click', removeTodo);
document.getElementById('sim').addEventListener('click', getData);
document.getElementById('headers').addEventListener('click', customHeaders);
document.getElementById('transform').addEventListener('click', transformResponse);
document.getElementById('error').addEventListener('error', errorHandle);
document.getElementById('cancel').addEventListener('click', cancelToken);