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

 

以上

相关文章
相关标签/搜索