生活随笔
收集整理的這篇文章主要介紹了
uni.request接口封装;小程序uni-app接口封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
另一篇請求接口簡單封裝在api下的index.js
本片資源下載地址
本片封裝了post get put請求,重點在request.js文件
1.新增四個文件
2.根目錄下的utils下的request.js封裝uni.request()請求
注意 :需要根據自己接口的 statusCode 狀態碼 、數據狀態碼 return_code 和提示信息 return_message 做對應替換
需要更改公共地址
需要注意store的token獲取
需要注意 封裝了get post put請求 需要其他的請求自行繼續封裝
import store
from '../store'let baseUrl
= ''
let isExisited
= falseconst $https
= {}switch (process
.env
.NODE_ENV) {case 'development':baseUrl
= 'http://172.17.2.112:8080/'breakcase 'test':baseUrl
= 'https://test.epen.ltd/'breakcase 'production':baseUrl
= 'https://production.epen.ltd/'breakdefault:baseUrl
= 'https://default.epen.ltd/'
}
console
.log('baseUrl', baseUrl
)function httpRequest(settings, opts) {const { loading
, hasToken
, toast
, checkToken
} = opts
const token
= uni
.getStorageSync('token_key')const hasUserInfo
= store
.getters
.hasUserInfo
if (hasToken
!== false) {settings
.header
['Token'] = token
}let showLoading
= loading
!== falseif (showLoading
) uni
.showLoading({ title
: '加載中...', mask
: true })return new Promise(function (resolve, reject) {uni
.request({...settings
,success: (res) => {const { statusCode
, data
} = resconsole
.log('接口返回的res', statusCode
, res
)if (showLoading
) uni
.hideLoading()switch (statusCode
) {case 200:breakcase 500:uni
.showToast({title
: data
.return_message
|| '服務器重啟中...',duration
: 2000,icon
: 'none',})returndefault:uni
.showToast({title
: data
.return_message
|| '請求失敗,請重試!',duration
: 2000,icon
: 'none',})return}const result
= res
.data
switch (result
.return_code
) {case '0':resolve(result
)breakcase '4011':uni
.clearStorage()if (hasUserInfo
&& !isExisited
&& !checkToken
) {isExisited
= trueuni
.showModal({title
: '提示',content
: '身份失效,請重新登錄!',complete: () => {uni
.reLaunch({ url
: '/pages/index/index' })},})} else {reject(result
)}breakdefault:reject(result
)if (toast
!== false) showErrors(result
)}},fail: (res) => {console
.log('請求fail', res
)if (showLoading
) uni
.hideLoading()uni
.showToast({title
: res
.return_message
|| '請求失敗,請重試!',duration
: 2000,icon
: 'none',})},})})
}function showErrors(res) {const { return_code
, return_message
} = res
switch (return_code
) {case 4004:uni
.showToast({title
: return_message
,duration
: 2000,icon
: 'none',})breakdefault:uni
.showToast({title
: return_message
|| '請求失敗',duration
: 2000,icon
: 'none',})}
}function setParams(params) {let result
= []for (let p
in params
) {result
.push(`${p}=${params[p]}`)}return '?' + result
.join('&')
}$https
.get = function (opts) {const { params
, data
, toast
, hasToken
, loading
, checkToken
} = opts
if (params
) opts
.url
= opts
.url
+ setParams(params
)let defaultOpts
= {url
: baseUrl
+ opts
.url
,data
: data
,method
: 'GET',header
: {'X-Requested-With': 'XMLHttpRequest',Accept
: 'application/json','Content-Type': 'application/json; charset=UTF-8',},dataType
: 'json',}return httpRequest(defaultOpts
, { loading
, toast
, hasToken
, checkToken
})
}$https
.put = function (opts) {const { params
, data
, toast
, hasToken
, loading
} = opts
if (opts
.params
) opts
.url
= opts
.url
+ setParams(opts
.params
)let defaultOpts
= {url
: baseUrl
+ opts
.url
,data
: data
,method
: 'PUT',header
: {'X-Requested-With': 'XMLHttpRequest',Accept
: 'application/json','Content-Type': 'application/json; charset=UTF-8',},dataType
: 'json',}return httpRequest(defaultOpts
, { loading
, toast
, hasToken
})
}$https
.post = function (opts) {const { params
, data
, toast
, hasToken
, loading
} = opts
if (params
) opts
.url
= opts
.url
+ setParams(params
)let defaultOpts
= {url
: baseUrl
+ opts
.url
,data
: data
,method
: 'POST',header
: {'X-Requested-With': 'XMLHttpRequest','Content-Type': 'application/json; charset=UTF-8',},dataType
: 'json',}return httpRequest(defaultOpts
, { loading
, toast
, hasToken
})
}export { $https
, baseUrl
}
3.pages/api/modules.js
注意:api下 一個模塊js文件 存放一個模塊的接口方法
import { $https
} from '../../utils/request'
export function getStudentList(params) {return $https
.get({url
: `main/stuWork/answersBySerial`,params
,loading
: false,})
}
export function getQuestionByWorkId(params) {return $https
.get({url
: `main/work/queStatus/${params.workId}`,})
}
export function getQuestionCorrectByWorkId(params) {return $https
.get({url
: 'main/resource/getQuestion',params
,})
}
export function submitCorrectAnswer(data) {return $https
.post({url
: `main/correction/subCorrResult`,data
,loading
: false,})
}
export function getExerciseInfo(id) {return $https
.get(`main/interaction/start/${id}`)
}
export function getProductcategory() {return $https
.get({url
: `api/v1/accident/productcategory/list`,})
}
export function getInsurancecompany(params) {return $https
.get({url
: `api/v1/accident/insurancecompany/list`,params
,})
}
export function postInsurance(data) {return $https
.post({url
: `api/v1/accident/insurance/list`,data
,})
}
4.請求vue頁面
<template
><view
><view
>objData
: {{objData
}}</view
><view style
="margin-top:50px;">arrData
:<view v
-for="item in arrData" :key
="item">{{item
}}</view
></view
><!-- <button type
="primary" @click
="get">原生請求
</button
><button type
="primary" @click
="getType">封裝后
async await獲取
</button
><button type
="primary" @click
="postType">封裝后
.then()獲取
</button
> -->..<button type
="primary" @click
="get1">utils完全封裝
--直接get
</button
><button type
="primary" @click
="get2">utils完全封裝
--參數get
</button
><button type
="primary" @click
="post1">utils完全封裝
--post參數
</button
></view
>
</template
><script
>
import { getProductcategory
, getInsurancecompany
, postInsurance
} from "../api/modules";
export default {data() {return {value
: 0,objData
: {},arrData
: []}},methods
: {get() {uni
.showLoading({title
: '加載中...',mask
: true,})uni
.request({url
: 'http://localhost:2222/yiiapp/order/list-all-web',data
: {refund_status
: 0,action
: 'multiple_orders',order_type
: 0,index
: 0,limit
: 10,status
: 3,key
: '',},header
: {Cookie
: '_uab_collina=162036568869229763220898; Hm_lvt_79ee0e9f63d4bd87c861f98a6d497993=1621240284,1621300029,1621410251,1621411597; PHPSESSID=mpmdmr4d7vneg6tpmmgm130gu1; user_id=3963; ZHBSESSID=e3aab6cf717a4d549c87735d0c39110e; Hm_lpvt_79ee0e9f63d4bd87c861f98a6d497993=1621504639'},method
: 'POST',success: (res) => {uni
.hideLoading()if (res
.statusCode
!== 200) {return uni
.showToast({title
: '獲取數據失敗',icon
: "none",mask
: true,})}console
.log('原生獲取res', res
);this.objData
= res
.data
.data
},fail: (error) => {uni
.hideLoading()uni
.showToast({title
: '請求接口失敗',icon
: "none",})console
.log(error
);}})},async getType() {const res
= await this.$myRequest({url
: 'yiiapp/order/list-all-web',})console
.log('使用async await獲取返回的參數', res
);this.objData
= res
.data
},postType() {this.$myRequest({url
: 'yiiapp/car-ins-stat/get-car-ins-stat',method
: 'POST',data
: {agency_id
: 125,stat_date_type
: '3',dim
: 'self-team-insurancecompany'}}).then(res => {console
.log('使用.then()獲取返回的參數', res
);this.arrData
= res
.data
})},changeType(e) {this.value
= e
.target
.value
},get1() {getProductcategory().then(res => {console
.log('res', res
);this.arrData
= res
.data
})},get2() {getInsurancecompany({ productCategory
: 7 }).then(res => {console
.log('res', res
);this.arrData
= res
.data
})},post1() {let obj
= {insuranceCompany
: "",insuranceName
: "",pageIndex
: 15,pageSize
: 1,productCategory
: ""}postInsurance(obj
).then(res => {console
.log('res', res
);this.arrData
= res
.data
})}}
}
</script
><style lang
="scss">
button
{width
: 260px
;margin
-top
: 2px
;
}
</style
>
5.成功接口請求:
6.失敗接口:
404提示:
接口調用成功200 但是data的狀態碼返回異常 做提示:
總結
以上是生活随笔為你收集整理的uni.request接口封装;小程序uni-app接口封装的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。