一.前言
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("請求失敗!")
}
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/12902.html
標籤:其他
