小程序单独封装axios请求
2020-09-09 09:59
1711 查看
一.前言
1.小程序自己有单独的请求api,并且小程序自己已经处理了跨域。
wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默认值=》请求他 }, success (res) { console.log(res.data) } })
但每次都这样请求不免麻烦,重复,所以我们自己封装一下。封装成axios请求
二.封装请求Api
class Axios { post(url, data, formType) { return this.request("POST", url, data, formType) } get(url, data, formType) { return this.request("GET", url, data, formType) } put(url, data, formType) { return this.request("PUT", url, data, formType) } update(url, data, formType) { return this.request("UPDATE", url, data, formType) } detete(url, data, formType) { return this.request("DELETE", url, data, formType) } request(method, url, data, formType) { return new Promise((resolve, reject) => { var comtentType = formType ? 'application/x-www-form-urlencoded' : 'application/json' wx.request({ url: "https://cp-app.cme-im.com/expo-server"+url, method:method, data:data, header: { "content-type": comtentType }, success(res) { resolve(res.data) }, fail(err) { reject(err) } }) }) } } module.exports = new Axios()
三.在项目中使用
1.新建一个当前页面请求的js文件,
2.引入自定义的axios方法
const axios=require("../utils/util")//引入axios module.exports={//将请求暴露出去 //获取首页轮播 getBanner(url,data){ return axios.post(url,{data:data},1) }, //创建订单接口 addSaveForJson(url,data){ return axios.post(url,data,0) } }
3.在想要使用的界面的js中引入这两个暴露的请求
const {getBanner,addSaveForJson} =require("../../api/loginApi")
4.解决异步
addOrder:async function(){ let date=new Date().getTime(); let result=await addSaveForJson("/system/prod/addSaveForJson",{ "orderType":this.data.swiperIdx, "signature":this.data.inputValue, "storeType":this.data.radio, "createBy":date.toString()//传递时间的转换 }) if(result.code == 200){ wx.setStorageSync('orderDate', date.toString())//存入本地 wx.switchTab({//跳转tab url: '/pages/Order/index' }) }else{ console.log("请求失败!") } },
相关文章推荐
- 实现axios的统一封装API,axios结果格式处理,vue组件的loading动画变量在axios请求的前后改变
- ImageLoader 单独封装(处理网络请求的图片,与默认图片、图片缓存’)
- 微信小程序request请求封装,验签代码实例
- 详解微信小程序网络请求接口封装实例
- 微信小程序(一)request请求封装
- 微信小程序网络请求的封装与填坑之路
- HttpURLConnection 单独封装网络请求工具类
- 小程序请求API接口,网络请求封装
- 小程序 ajax请求封装
- 【微信小程序】网络请求接口封装实例
- vue中的promise封装axios请求和小程序封装request请求
- 微信小程序 封装请求
- axios 真机调试报错:TypeError: adapter is not a function,h5正常,解决方法?axios接口封装,uniapp接口封装,vue接口封装,请求拦截,请求返回拦截
- 封装axios请求
- 微信小程序网络请求的封装与填坑之路
- Vue项目中对axios进行封装以及api接口请求
- 小程序请求封装
- 微信小程序mpvue中封装axios(js或ts适用)
- vue中使用axios+Promise二次封装ajax请求
- 微信小程序入门 请求的封装