# 小程序封装请求

公司最近新开了小程序项目, 参考axios 重新封装了请求, 直接套用即可,有问题随时联系

# http.js

import InterceptorManager from './interceptor.js'
import dispatchRequest from './dispatchRequest.js'

/**
 * Create a new instance of httpRequest
 *
 */
function httpRequest(){
  this.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
  }
}

/**
 * Dispatch a request
 */

httpRequest.prototype.request = function request(config){

  // 连接拦截器中间件
  let chain = [dispatchRequest,undefined]
  let promise = Promise.resolve(config)

  // 注册请求拦截器
  this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor){
    chain.unshift(interceptor.fulfilled, interceptor.rejected)
  })

  // 注册响应拦截器
  this.interceptors.response.forEach(function pushResponseInterceptors(interceptor){
    chain.push(interceptor.fulfilled, interceptor.rejected)
  })

  while (chain.length){
    promise = promise.then(chain.shift(),chain.shift())
  }

  return promise
}

function createInstance() {
    let context = new httpRequest();
    return context
}

const $http = createdInstance()

export default $http

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# dispatchRequest.js

let detafultConfig = {
    headers: {
        'x-token': 'xxxx12token'
    },
    params: {
        id: 1
    }
}
let utils = require('../utils/util.js')
function combination(config) {
  let combConfig
  if (config.method === 'GET') {

    combConfig = Object.assign(detafultConfig, config.params)
    delete config.params
    let url = utils.createdQueryWidthUrl(combConfig,config.url)
    combConfig = Object.assign(config, {url: url})

  } else if (config.method === 'POST') {

    let data = Object.assign(detafultConfig, config.data)
    combConfig = Object.assign(config, {data: data})
    
  } else {
    combConfig = config
  }
  return combConfig
}

/**
 * 向服务器发送请求
 * @param {object} config 发起请求的数据
 * @returns {Promise}
 */

module.exports = function dispatchRequest(config){
  let combconfig = combination(config);
  return new Promise((resolve,reject)=>{
    combconfig = Object.assign(combconfig, {
      success:function(res){
        resolve(res)
      },
      fail:function(res){
        reject(res)
      },
      complete:function(res){
        reject(res)
      }
    });
    wx.request(combconfig)

  }).then(function onAdapterResolution(response){
    return response
  },function onAdapterRejection(reason){
    return Promise.reject(reason)
  })
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

# interceptor.js

function InterceptorManager() {
    this.handlers = []
}
/**
 * 向堆栈中添加新的拦截器
 *
 */
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
    this.handlers.push({
        fulfilled: fulfilled,
        rejected: rejected
    });
    return this.handlers.length - 1
}
// 迭代所有已注册的拦截器
InterceptorManager.prototype.forEach = function forEach(fn) {
    function forEachHandler(h) {
        if (h !== null) {
            fn(h);
        }
    }
    for (var i = 0, l = this.handlers.length; i < l; i++) {
        forEachHandler(this.handlers[i])
    }
}
export default InterceptorManager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# index.js

import $http from './http.js'

$http.interceptors.request.use(
  async function onFulfilled(config){
    wx.showLoading({
      title: '22',
    })
    return config
  },
  function onRejected(config){
    console.log('config拦截器失败了')
  }
)

$http.interceptors.response.use(
  function onFulfilled(response){
    wx.hideLoading()
    const code = +response.data.code
    switch (code) {
        code 401:
        // .....
        code 500:
        // .....
    }
  },
  function onRejected(reason){
    console.log('我是拦截器失败')
    wx.hideLoading()
  }
)
export default $http
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# Example

// get
axios.get('/test')
  .then(function (response) {
    console.log(response)
  })
  .catch(function (error) {
    console.log(error)
})
// post
axios.post('/user', {
    name: 'thorn',
    possword: '111'
  })
  .then(function (response) {
    console.log(response)
  })
  .catch(function (error) {
    console.log(error)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Last Updated: 11/7/2019, 10:35:59 AM