日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

微信小程序request请求封装;微信小程序封装request请求;uni-app小程序封装request请求;

發(fā)布時(shí)間:2023/12/9 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 微信小程序request请求封装;微信小程序封装request请求;uni-app小程序封装request请求; 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本片封裝了微信小程序request請(qǐng)求;為別是post get put請(qǐng)求,重點(diǎn)在request.js文件

1.新增四個(gè)文件

2.根目錄下的utils下的request.js封裝uni.request()請(qǐng)求

2.1 manifest.json:解決H5瀏覽器跨域問(wèn)題

// 自定義配置H5"h5": {"devServer": {"disableHostCheck": true, // 開(kāi)啟可以用自己的域名"proxy": {"/api": {"target": "https://www.zuihuibao.cn","changeOrigin": true,"secure": false,"pathRewrite": {//匹配請(qǐng)求路徑里面有 /api 會(huì)替換成https://www.zuihuibao.cn// url: `/yiiapp/keduoduo/system/send-sms`, 會(huì)被代理帶 https://www.zuihuibao.cn/yiiapp/keduoduo/system/send-sms"^/api": ""}}}}}

2.2utils文件的request.js:
注意 :需要根據(jù)自己接口的 statusCode 狀態(tài)碼 、數(shù)據(jù)狀態(tài)碼 return_code 和提示信息 return_message 做對(duì)應(yīng)替換
—需要更改公共地址
—需要注意store的token獲取
—需要注意 封裝了get post put請(qǐng)求 需要其他的請(qǐng)求自行繼續(xù)封裝

—包含了針對(duì)某個(gè)特殊接口url 做特殊的錯(cuò)誤提示(例如:settings.url.indexOf(‘system/ocr’)>=0)

import store from '../store'let baseUrl = '' let isExisited = falseconst $https = {}switch (process.env.NODE_ENV) {case 'development':// 公共的地址開(kāi)發(fā)--(為了兼容微信小程序和谷歌瀏覽器H5 故有以下兩個(gè) H5方便瀏覽器調(diào)試)/* #ifdef MP-WEIXIN */baseUrl = 'https://www.zuihuibao.cn/'/* #endif *//* #ifdef H5 */// 修改成如下判斷是為了解決 編譯H5瀏覽器跨域問(wèn)題 同時(shí)需要配置manifest.json文件的H5baseUrl = process.env.NODE_ENV === 'development' ? '/api' : 'https://www.zuihuibao.com' // 將否的改成生產(chǎn)環(huán)境/* #endif */breakcase 'test':baseUrl = 'https://www.zuihuibao.cn/'breakcase 'production':baseUrl = 'https://www.zuihuibao.com/'breakdefault:baseUrl = 'https://www.zuihuibao.com/' } console.log('baseUrl', baseUrl,process.env.NODE_ENV)function httpRequest(settings, opts) {const { loading, hasToken, toast, checkToken } = optsconst hasUserInfo = store.getters.hasUserInfosettings.header['aaaa'] = 'aaaa'// if (hasToken !== false) {if (hasToken) {const token = uni.getStorageSync('token_key')// settings.header['Token'] = tokenlet headerName = uni.getStorageSync('login_cookie_name') || 'login_cookie_name'let headerValue = uni.getStorageSync('login_cookie_value')|| ''// let headerName = store.getters.login_cookie_name || 'login_cookie_value'// let headerValue = store.getters.login_cookie_value || 'login_cookie_value'// console.log('設(shè)置cookie', store.getters, headerName, headerValue)// 針對(duì)需要token的接口(是否需要看接口傳參) 設(shè)置獲取登錄成功后的token 設(shè)置在header上settings.header['Cookie'] =`${headerName}=${headerValue}`// 根據(jù)是否有token的值 來(lái)判斷登陸是否有效(需要token 但是緩存沒(méi)有 就重定向到登錄頁(yè)) 退出時(shí)候清除tokenif (!headerValue) {// uni.showModal({// title: '提示',// content: '身份失效,請(qǐng)重新登錄!',// complete: () => {// uni.reLaunch({ url: '/pages/tabBar/login/index' })// },// })uni.reLaunch({ url: '/pages/tabBar/login/index' })return}}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()// 判斷 statusCode 是否是200 查看接口調(diào)用是否成功switch (statusCode) {case 200:breakcase 500:// reject({ statusCode: 500, return_message: '服務(wù)器重啟中...' })uni.showToast({title: data.return_message || '服務(wù)器重啟中...',duration: 2000,icon: 'none',})returndefault:// reject({ statusCode: statusCode, return_message: '請(qǐng)求失敗' })uni.showToast({title: data.return_message || '請(qǐng)求失敗,請(qǐng)重試!',duration: 2000,icon: 'none',})return}//在接口200 調(diào)用成功后 才能進(jìn)行判斷接口內(nèi)的狀態(tài)碼 return_code 以此判定作何操作和提示const result = res.dataswitch (result.return_code) {case '0':// 成功的數(shù)據(jù)data狀態(tài)碼 則直接返回?cái)?shù)據(jù)// console.log(1111111,result);resolve(result)breakcase '-1004':// 針對(duì)識(shí)別的接口方法getocr system/ocr做了特殊的錯(cuò)誤處理(需要用到這錯(cuò)誤修改頁(yè)面信息)if (settings.url.indexOf('system/ocr')>=0) {// console.log('settings',settings);// console.log('result',result);// 特定接口特定處理-在具體的組件返回的res判斷處理resolve(result)} else {// 正常接口報(bào)錯(cuò) 繼續(xù)提示showErrors(result)}breakcase '-1':// 這個(gè)是特殊的失敗數(shù)據(jù) 需要接口返回特殊處理resolve(result)breakcase '-1000'://登錄失效 清除所有緩存 退到登錄頁(yè)uni.clearStorage()if (hasUserInfo && !isExisited && !checkToken) {isExisited = trueuni.showModal({title: '提示',content: '身份失效,請(qǐng)重新登錄!',complete: () => {uni.reLaunch({ url: '/pages/tabBar/login/index' })},})} else {reject(result)}breakdefault:reject(result)if (toast !== false) showErrors(result)}},fail: (res) => {// console.log('請(qǐng)求fail', res)if (showLoading) uni.hideLoading()uni.showToast({// title: '請(qǐng)求失敗,請(qǐng)重試1122!',title: res.return_message || '請(qǐng)求失敗,請(qǐng)重試!',duration: 2000,icon: 'none',})},})}) }function showErrors(res) {const { return_code, return_message } = resswitch (return_code) {case -1004:uni.showToast({title: return_message,duration: 2000,icon: 'none',})breakdefault:uni.showToast({title: return_message || '請(qǐng)求失敗',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 } = optsif (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 } = optsif (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 } = optsif (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 }

2.3.某個(gè)模塊的接口請(qǐng)求方法api:

hasToken: false,既不需要token ;
params是url拼接傳參;
loading:false,既不存在loading刷新提示(可以通過(guò)在api方法內(nèi)寫(xiě)死,也可以通過(guò)vue頁(yè)面的傳參獲取動(dòng)態(tài)的);
data是正常傳參

/* // post兩種請(qǐng)求 data和params// function query(data, params, opts) { // return $https.get({url, data, params, ...opts}) // return $https.post({url, data, params, ...opts}) // } // ``` // url: 'main/work/list' // data為{}請(qǐng)求參數(shù), // params為{},最后更改為url傳參 // 默認(rèn)情況下,接口會(huì)傳token, 加載框會(huì)顯示,請(qǐng)求失敗信息toast會(huì)展示, // 如需自定義,可以傳入opts: {loading: false, hasToken: false, toast: true} // 其中l(wèi)oading為false, 接口請(qǐng)求時(shí)不顯示loading框 // hasToken為false, 請(qǐng)求不需要帶token // toast為false,請(qǐng)求失敗不會(huì)顯示系統(tǒng)toast// ``` */ import { $https } from '../../utils/request'// 根據(jù)手機(jī)號(hào)注冊(cè)或登錄 export function loginByMobile(params,loading) {return $https.post({url: 'yiiapp/keduoduo/system/login-by-mobile',params,hasToken: false,loading:loading == false ? false : true //注意在vue頁(yè)面?zhèn)鬟f第二個(gè)參數(shù)就是loading的值(同理hasToken也可以如此處理)}) }// 根據(jù)手機(jī)號(hào)注冊(cè)或登錄 export function customerList(params) {return $https.post({url: 'yiiapp/keduoduo/customer/customer-list',params,hasToken: true,}) }// 查看我的信息 export function getMyInfo(params) {return $https.post({url: 'yiiapp/keduoduo/user/my-info',params,hasToken: true,}) }// 提交報(bào)價(jià)申請(qǐng) export function submitPriceRecord(params) {return $https.post({url: 'yiiapp/keduoduo/customer/submit-price-record',params,hasToken: true,}) }// 刪除車(chē)輛 export function deleteCarInfo(params) {return $https.post({url: 'yiiapp/keduoduo/car-info/delete-car-info',params,hasToken: true,}) }// 直接get獲取 export function getProductcategory() {return $https.get({url: `api/v1/accident/productcategory/list`,}) } // get參數(shù)獲取 export function getInsurancecompany(params) {return $https.get({url: `api/v1/accident/insurancecompany/list`,params,}) } // post參數(shù)請(qǐng)求 export function postInsurance(data) {return $https.post({url: `api/v1/accident/insurance/list`,data,}) }

4.請(qǐng)求vue頁(yè)面

<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">原生請(qǐng)求</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完全封裝--參數(shù)get</button><button type="primary" @click="post1">utils完全封裝--post參數(shù)</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: {// 使用公眾號(hào)的CookieCookie: '_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: '獲取數(shù)據(jù)失敗',icon: "none",mask: true,})}console.log('原生獲取res', res);this.objData = res.data.data},fail: (error) => {uni.hideLoading()uni.showToast({title: '請(qǐng)求接口失敗',icon: "none",})console.log(error);}})},async getType() {const res = await this.$myRequest({url: 'yiiapp/order/list-all-web',})console.log('使用async await獲取返回的參數(shù)', 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()獲取返回的參數(shù)', res);this.arrData = res.data})},changeType(e) {// console.log(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.成功接口請(qǐng)求:

6.失敗接口: 404提示:

接口調(diào)用成功200 但是data的狀態(tài)碼返回異常 做提示:

總結(jié)

以上是生活随笔為你收集整理的微信小程序request请求封装;微信小程序封装request请求;uni-app小程序封装request请求;的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。