小程序版结合promise的axios风格ajax请求函数。

建议的小程序版本的axios函数,之所以说简易,因为只是用了常用的请求方法外,然后添加了拦截器而已。
具体如下:

下载,安装

npm i cdd-lib

使用

es6:

import {wxhttp} from 'cdd-lib'

commonjs:

let {wxhttp} = require('cdd-lib')

wxhttp


命名为wxhttp

具体的请求用法如axios

wxhttp#request(config)

wxhttp#get(url[,config])

wxhttp#delete(url[,config])

wxhttp#head(url[,config])

wxhttp#options(url[,config])

wxhttp#post(url[,data[,config]])

wxhttp#put(url[,data[,config]])

wxhttp#patch(url[,data[,config]])

拦截方法:

  1. 请求拦截

wxhttp.interceptors.request.use(handleRequest(config),handleError(err))

注意:handleRequest需要返回处理后的config

  1. 返回拦截

wxhttp.interceptors.response.use(handresponse(res))

注意:handleResponse需要返回处理后的res

例子:

import $http from "../../utils/http"
export default {
  name: 'seckillHome',
  data() {
    return {

    }
  },
  onShow() {
    // 请求拦截
    $http.interceptors.request.use(function (config) {
      console.log(`请求拦截`, config)
      // 此处设置的数据将与请求的数据进行合并,如果自动同名则以拦截的为准。
      config.data = {
        address: "北京市东城区"
      }
      return config
    })

    $http.post('https://www.baidu.com', {
      name: 'cdd',
      age: 23
    }).then(res => {
      console.log(`结果是`, res)
    })
  }
}

因为使用了promise风格,所以可以使用Promise.all方法来进行并发请求。

查看源码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值