axios 請求攔截封裝使用

1. 引入axios node

import axios from 'axios'

2. 引入接口 api ios

import API from './api'

接口 api 格式以下es6

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. 配置本地測試和線上的請求域名json

  a. node 環境能夠用  process.env.NODE_ENV 來判斷是否是在本地環境,axios

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

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

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

4. 配置全局參數promise

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 })

 

以上

相關文章
相關標籤/搜索