Axios(IE8+)
基於promise的http庫
可用於瀏覽器與node.js
1.特性
- 支持promise API
- 攔截請求和相應
- 轉換請求數據和響應數據
- 取消請求
- 自動轉換JSON數據
- 客戶端支持防御XSRF攻擊
2.axios請求方法:get,post,put, patch, delete
1get: 獲取數據
2post(新建): 提交數據(表單,文件)
3put(更新): 更新數據(所有數據推送到后端)
4patch(耗性能): 更新數據(只將修改的數據推送到后端)
5delet: 刪除數據
3.返回304(重定向)
表示重復的請求,直接返回304,加快請求速度
4.post(Content-Type)
11.form-data 表單提交(文件上傳)
22.application/json 常用數據提交
3
4//form-data請求舉例
5let formData = new FormData()
6for(let key in data){
7 formData.append(key,data[key])
8}
5.並發請求(同時進行多個請求,並統一處理返回值)
1//axios.all() 用於多個請求並發
2//axios.spread() 用於處理返回值
3
4axios.all(
5 [
6 axios.get('/data.json1'),
7 axios.get('/data.json2')
8 ]
9).then(
10 axios.spread((json1,json2)=>{
11 console.log(json1,json2)
12 })
13)
6.axios實例化
當每請求的設置不盡相同時,可以通過配置實例發起不同設置的請求
1let instance = axios.create({
2 baseURL: 'http://localhost:8080',
3 timeout: 1000,
4})
5instance.get('/data.json').then(res=>{
6 console.log(res)
7})
7.axios配置
- 全局配置
11.axios.defaults.timeout = 2000
22.axios.defaults.baseURL = ''
- 實例配置
1let instance = axios.create({
2 //配置
3 baseURL: 'http://localhost:8080',//請求的域名,基本地址
4 timeout: 1000,//超時取消請求時長(ms),一般后台會有定義
5 url: '/data.json',//請求路徑
6 method: 'get',//get,post,put, patch, delete(請求方法)
7 headers: {//設置請求頭
8 token: '',//身份信息
9 },
10 params: {},//請求參數拼接在url(get)
11 data: {},//請求參數放在請求體(post)
12})
13instance.defaults.timeout = 3000
- 請求配置
1instance.get('/data.js',{
2 timeout: 5000
3})
- 優先級
請求配置>實例配置>實例配置
8.攔截器
在請求或響應被處理前攔截他們
- 請求攔截器
1axios.interceptors.request.use(
2 config => {
3 //發送請求前
4 return config
5 },
6 err => {//錯誤處理
7 //請求錯誤的時候 404 not find,401超時等
8 return Promise.reject(err)
9 }
10)
- 響應攔截器
1axios.interceptors.response.use(
2 res => {
3 //請求成功
4 return res
5 },
6 err => {//錯誤處理
7 //響應錯誤的時候 500服務器錯誤等
8 return Promise.reject(err)
9 }
10)
- 取消攔截器
1axios.interceptors.request.eject(interceptors)
9.取消請求
1let source = axios.CancelToken.source() //創建實例
2axios.get('/data.js',{//開始請求
3 cancelToken: source.token//配置項
4}).then(res => {
5 console.log(res)
6}).catch(err => {
7 console.log(err)
8})
9
10source.cancel('請求取消了')//調用方法取消請求
10.統一封裝(async await 方法)
api.js接口信息
1//api.js接口信息
2const api = {
3 api1: {
4 method: 'get',
5 url: '/data1.js
6 },
7 api2: {
8 method: 'post',
9 url: '/data2.js
10 }
11}
12export default api
http.js請求對象
1import axios from 'axios'
2import Api from 'api.js'
3
4let instance = axios.creat({
5 baseURL: 'http://localhost:8080',
6 timeout: 1000
7})
8const Http = {}//包裹請求方法的容器
9
10for(let key in Api){
11 let api = Api[key]
12 Http[key] = async function(
13 params,//請求參數
14 isFormData=false,//是否是form-data請求
15 config={}//配置參數
16 ){
17 let newParams = {}
18
19 //判斷content-type是不是form-data類型
20 if(params && isFormData){
21 newParams = new FormData()
22 for(let i in params){
23 newParams.append(i,params[i])
24 }
25 }else newParams = params
26
27 //不同請求的判斷
28 let res = {}
29 if(api.method === 'put' || api.method === 'post' || api.method === 'patch'){
30 try{
31 res = await instance[api.method](api.url,newParams,config)
32 }catch(err){
33 res = err
34 }
35 }else if(api.method === 'delete' || api.method === 'get'){
36 config.params = newParams
37 try{
38 res = await instance[api.method](api.url,config)
39 }catch(err){
40 res = err
41 }
42 }
43 return res //返回響應值
44 }
45}
46//請求攔截器
47instance.interceptors.request.use(
48 config => {
49 //發起請求前
50 Toast.loading()
51 return config
52 },
53 err => {
54 //請求錯誤
55 Toast.clear()
56 return err
57 }
58)
59//響應攔截器
60instance.interceptors.response.use(
61 res => {
62 //響應前
63 Toast.clear()
64 return res.data
65 },
66 err => {
67 //響應錯誤
68 Toast.clear()
69 return err
70 }
71)
72
73export default Http
調用方法
1import Http from 'http.js'
2Vue.prototype.$Http = Http
3
4async function(){
5 let res = await this.$Http.api1({id: 4})
6}
7
8async function(){
9 let res = await this.$Http.api2(info,true,config)
10}
