Axios
Axios 是一個基于 promise 網路請求庫,作用于node.js 和瀏覽器中, 它是 isomorphic 的(即同一套代碼可以運行在瀏覽器和node.js中),在服務端它使用原生 node.js http 模塊, 而在客戶端 (瀏覽端) 則使用 XMLHttpRequests,
服務器端
使用json-server
1. axios基本使用
// 1.GET
axios({
method: 'GET',
url: 'http://localhost:3000/posts/2'
}).then(res => {
console.log(res);
})
// POST
axios({
method: 'POST',
url: 'http://localhost:3000/posts',
data: {
title: 'test',
author: 'lll'
}
}).then(res => {
console.log(res);
})
// PUT
axios({
method: 'PUT',
url: 'http://localhost:3000/posts/3',
data: {
title: 'test',
author: 'new-lll'
}
}).then(res => {
console.log(res);
})
// DELETE
axios({
method: 'DELETE',
url: 'http://localhost:3000/posts/3',
}).then(res => {
console.log(res);
})
2. 其他請求方法
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
// request
axios.request({
method: 'GET',
url: 'http://localhost:3000/posts/2'
}).then(res => {
console.log(res)
})
// POST
axios.post(
'http://localhost:3000/comments',
{
"body": "other",
"postId": 2
}
).then(res => {
console.log(res)
})
3. axios默認配置
// default setting
axios.defaults.method = 'GET'
axios.defaults.baseURL = 'http:localhost:3000'
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
4. axios創建實體物件
// 創建實體物件
const obj = axios.create({
baseURL: 'http://localhost:3000'
})
// obj實體和axios物件幾乎相同
obj({
url: 'posts/2'
}).then(res => {
console.log(res)
})
5. axios攔截器
/**
* 攔截器實質是函式
* 請求攔截器,在請求發出時檢查請求的引數等是否正確
* 回應攔截器,在接受回應前,對回應進行預處理
*/
// 請求攔截器
axios.interceptors.request.use(functio(config) {
console.log('req success')
return config
}), function (error) {
console.log('req fail')
return Promise.reject(error)
}
// 接收攔截器
axios.interceptors.response.use(functio(response) {
console.log('res success')
return response;
}, function (error) {
console.log('res fail')
return Promise.reject(error);
});
6. 取消請求
let cancel = nul
btns[0].onclick = function () {
// 檢查上一個請求是否結束
if (cancel !== null) {
cancel()
}
axios({
url: '/posts',
cancelToken: new axios.CancelTok(function executor(c) {
cancel = c;
})
}).then(res => {
cancel = null
console.log(res)
})
btns[1].onclick = function () {
cancel()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/543318.html
標籤:JavaScript
上一篇:JavaScript 高階函式
下一篇:JavaScript進階
