您当前的位置: 首页 > 解决方案

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

  • 作者: admin
  • 发布于 2018-10-20 13:50:50
  • 来源:  
  • 栏目:解决方案

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

 

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

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方法来进行并发请求。

查看源码



温馨提示:这篇文章没有解决您的问题?欢迎添加微信:18948083295,有微信小程序专业人员,保证有问必答。转载本站文章请注明转自http://www.okeydown.com/(微信小程序网)。

  • 微信扫描二维码关注官方微信
  • ▲长按图片识别二维码
关注我们

微信小程序官方微信

栏目最新
栏目推荐
返回顶部