加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

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

发布时间:2020-12-14 19:32:22 所属栏目:资源 来源:网络整理
导读:建议的小程序版本的axios函数,之所以说简易,因为只是用了常用的请求方法外,然后添加了拦截器而已。 具体如下: wxhttp 命名为 wxhttp 具体的请求用法如axios wxhttp#request(config) wxhttp#get(url[,config]) wxhttp#delete(url[,255);'> wxhttp#head(ur

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

wxhttp


命名为wxhttp

具体的请求用法如axios

wxhttp#request(config)

wxhttp#get(url[,config])

wxhttp#delete(url[,255);'>wxhttp#head(url[,255);'>wxhttp#options(url[,255);'>wxhttp#post(url[,data[,config]])

wxhttp#put(url[,255);'>wxhttp#patch(url[,255);'>拦截方法:

  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 => {
      `结果是`,res)
    })
  }
}

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

查看源码

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读