axios 請求攔截封裝使用


1. 引入axios 

import axios from 'axios'

2. 引入接口 api 

import API from './api'

接口 api 格式如下

1 {
2   "userInfo": {
3        "query": "xxx/xxx/userInfo/query",  
4        "update": "xxx/xxx/userInfo/update",  
5    },
6     "xxx": {
7         "xxx": "xxx/xxx/xxx/xxx"
8    }
9 }

3. 配置本地測試和線上的請求域名

  a. node 環境可以用  process.env.NODE_ENV 來判斷是不是在本地環境,

  b. 不是node 環境就用你的本地域名判斷吧, 127.0.0.1 localhost 什么的

  c. 有配置代理跨域的 devOrigin 配上你的代理名

1 const devOrigin = 'http://test.yuming.com' // 本地開發接口地址
3 // 正式環境動態獲取域名
4 const Host = process.env.NODE_ENV === 'development' ? devOrigin : window.location.origin

4. 配置全局參數

1 axios.defaults.headers['Content-Type'] = 'application/json'   // 全局請求頭
2 axios.defaults.headers['publicParams'] = '******' // 如果要設置公參也可以放在請求頭里
3 axios.defaults.baseURL = Host // 配置請求域名第3步拿到的域名
4 axios.defaults.timeout = 10000 // 配置超時時間

5. 設置全局的請求攔截和響應攔截

 1 // 請求攔截
 2 axios.interceptors.request.use(function (config) { 
 3    // 請求已經到了服務器那邊
 4    // config 是請求時攜帶的一些信息可以打印下看看具體的 
 5 }, function (error) {
 6    // 請求出現了錯誤,一般可能時客戶端網絡出現問題 
 7 })
 8 
 9 // 響應攔截
10 axios.interceptors.response.use(function (res) { 
11    // 接口返回200這里需要 return 返回的信息,不然請求的時候拿不到服務器返回的信息
12 }, function (error) {
13    // 響應非200,或者超過了設定的請求時間而超時了
14 })

 6. 向外部暴露請求方法

  a. post 請求如下

 1 export const httpPost = (url, params, config = {}) => {
 2   const [key1, key2] = url.split('/')
 3   let urls
 4   if (API[key1]) {
 5     urls = API[key1][key2]
 6   } else {
 7     urls = url
 8   }
 9   let data = {
10         xxx: 'xxx' // 這里可以添加公共參數,比如appid什么的
11         ...params
12       }    
13   }
14   return axios({
15     url: urls,
16     method: 'post',
17     data: data,
18     ...config  
19   })
20 }

     b. get 請求如下, 這里也可以像post 請求一樣使用將請求參數放在第二個參數里,參數格式用json 格式,就是這里配置請求url 的時候需要把json 拼接成 search 格式的參數

 1 export const httpGet = (url, params = {}, config = {}) => {
 2   const [key1, key2] = url.split('/')
 3   let urls
 4   if (API[key1]) {
 5     urls = API[key1][key2]
 6   } else {
 7     urls = urlKeys
 8   }
 9   axios({
10     url: urls,
11     params: {
12        ...params
13     }  
14     method: 'get',
15     ...config
16   })
17 }

 

7. 頁面發起請求

a. 支持 es6

1 async function getUserInfo () { // 可以使用 try catch 拿到請求出錯信息
2    let res = await httpGet('userInfo/query', {userId: 123})  // get 請求
3    let res2 = await httpPost('userInfo/update', { // post 請求
4       name: 'haha'
5    }) 
6 }

b. promise 寫法

1 httpPost('userInfo/update', {
2   name: 'haha'
3 }).then(result => {
4   // result   響應攔截返回的信息
5 }).catch(error => {
6    // 請求出錯
7 })

 

以上

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM