一 Axios的概念
Axios是什么?
Axios是一個基於promise的HTTP庫,主要用於瀏覽器和node.js。
Axios有哪些特性?
- 支持Promise API
- 攔截請求和響應請求
- 轉換請求數據和響應數據(請求是可以加密,在返回時也可進行解密)
- 取消請求
- 自動轉換JSON數據(無需手動操作)
- 客戶端支持防御XSRF攻擊
Axios常用的請求方法?
- get:獲取數據
- post :提交數據,表單提交或文件上傳等。
- put :更新數據(所有數據推送到后端)
- patch :更新數據(只將修改的數據推送到后端)
- delete:刪除數據
Axios的安裝與引用:
npm add axios // 安裝axios
import axios from "axios"; // 引用axios
Axios的請求方法demo:
get:
// 寫法一 axios.get("https://api.thecatapi.com/v1/images/search", { params: { limit: 1, page: 10, order: "Desc", }, }) .then((res) => { console.log(res); }); // 寫法二 axios({ method: "get", url: `https://api.thecatapi.com/v1/images/search?limit=${1}&page=${10}&order=${"Desc"}`, }).then((res) => { console.log(res); });
post:
post的兩種請求格式:
form-data (常用於文件/圖片上傳):content-type: multipart/form-data; boundary=----WebKitFormBoundaryK0A5EtRCDRaTJb7x boundary(后端解碼內容)
application/json 常用格式,如data:content-type: application/json; charset=utf-8
// 請求方式一:application/json // 寫法一 let dataTest = { image_id: "asf2", sub_id: "my-user-1234", value: 1, }; axios.post("https://api.thecatapi.com/v1/votes", dataTest).then((res) => { console.log(res); });
// 請求方式二:form-data // 寫法二 let formData = new FormData(); formData.append("image_id", "asf2"); formData.append("sub_id", "my-user-1234"); formData.append("value", '1'); axios({ method: "post", url: "https://api.thecatapi.com/v1/votes", data: formData, // params 參數在請求體內 }).then((res) => { console.log(res); });
delete:
let vote_id = '318737' axios.delete(`https://api.thecatapi.com/v1/votes/${vote_id}`).then(res=>{ console.log(res) })
Axios並發方法:
並發請求:同時進行多個請求,並統一處理返回值。
// axios.all() 是一個數組,存放axios請求,數組順序即請求數據 // axios.spead() 是多個請求(axios.all())完成后,對它的返回數據進行分割處理 axios.all([ axios.get(`https://api.thecatapi.com/v1/images/search?limit=${1}&page=${10}&order=${"Desc"}`), axios.get('https://dog.ceo/api/breeds/image/random') ]).then( // 並發的then不能只寫一個回調請求 axios.spread((catApi,dogApi)=>{ console.log(catApi,dogApi) }) )
Axios 實例:
axios通過創建axios.create實例。
let instance = axios.create({ baseURL:'http://localhost:8080', timeout:1000 }) instance.get('https://dog.ceo/api/breeds/image/random').then(res=>{ console.log(res) })
Axios 實例相關配置:
- baseURL:請求的基礎地址,請求接口時會拼接在baseURL后面
- timeout:請求的超時時長(毫秒),如果請求的數據量比較大,會堵塞后端內容,然后超時釋放超時內容。
- url:請求的路徑
- method:請求的方法,get,post,pull,patch,delete
- headers:請求頭,存放token。
- params:請求參數拼接在url上
- data:請求參數拼接在請求體內
let instance = axios.create({ baseURL:'http://localhost:8080', timeout:1000, url:'', method:'get', headers:{ token:'' }, params:{}, data:{} })
Axios配置的三種方式:
- 全局配置:axios.defaults
- 實例配置:axios.create,如果不添加參數則默認使用全局配置
- 請求配置:用於處理一些特殊接口,如數據量比較大,需要單獨增加超時時長
- 配置優先級:全局配置 < 實例配置 < 請求配置
// 1.axios全局配置 axios.defaults axios.defaults.baseURL = 'http://localhost:8080' axios.defaults.timeout = 1000 // 2.axios實例配置,如果不添加參數則默認使用全局配置 let instance2 = axios.create({}) // 3.axio請求配置,用於處理一些特殊接口,如數據量比較大,要單獨增加超時時長 instance.get('https://dog.ceo/api/breeds/image/random',{ timeout:5000 }).then(res=>{ console.log(res) })
Axios請求多個域名接口:
// Axios請求多個域名接口: let instance = axios.create({ baseURL:'http://localhost:8080', timeout:1000, }) let instance2 = axios.create({ baseURL:'http://localhost:8081', timeout:3000, }) // 請求不同的域名接口 instance.get('/').then(()=>{console.log}) instance2.get('/',{timeout:5000}).then(()=>{console.log})
Axios攔截器:
- 攔截器:在請求或響應被處理前攔截它們
- 請求攔截器:在前端發起請求前處理
- 響應攔截器:在后端響應請求后處理
- 取消攔截器(不常用)
// 請求攔截器:在前端發起請求前處理 axios.interceptors.request.use( (config) => { // 發送請求前做些什么,如判斷是否有token return config; }, (Error) => { // 請求錯誤時返回 return Promise.reject(Error); } );
// 響應攔截器:在后端響應請求后處理 axios.interceptors.response.use( (res) => { // 請求成功后做些什么,如判斷后端返回的code狀態碼 return res; }, (Error) => { // 響應錯誤做些什么 return Promise.reject(Error); } ); instance.get("/").then((res) => { console.log(res); }); // then請求失敗 instance2.get("/", { timeout: 5000 }).catch((Error) => { console.log(Error); }); // catch請求失敗
// 取消攔截器(不常用) let interceptors = axios.interceptors.response.use((config) => { // 請求之前可以在headers中新增auth參數 config.headers = { auth: true, }; return config; }); // 取消headers中的auth axios.interceptors.request.eject(interceptors);
Axios攔截器demo:
請求與響應攔截器的處理
// 例一:登錄(token) let instance3 = axios.create({}); // 訪問需要token的接口 instance3.interceptors.request.use((config) => { config.headers.token = "登錄返回的token"; return config; }); let instance4 = axios.create({}); // 訪問不需要token的接口 // 例二:請求中的loading提示 let instancePhone = axios.create({}); instancePhone.interceptors.request.use((config) => { // $('#loading').show 加載中打開 return config; }); instancePhone.interceptors.response.use((res) => { // $('#loading').hide 加載中關閉 return res; });
Axios取消請求
// Axios取消請求 // source()方法生成了一個取消請求的CancelToken、 let source = axios.CancelToken.source() axios.get('/data.json',{ cancelToken:source.token }).then(res=>{ console.log(res) }).catch(err=>{ console.log(err,) }) // 取消請求,cancel中的參數會進入到catch中。cancel('參數可選') source.cancel('cancel http')