本片封装了微信小程序request请求;为别是post get put请求,重点在request.js文件
1.新增四个文件
2.根目录下的utils下的request.js封装uni.request()请求
2.1 manifest.json:解决H5浏览器跨域问题-----配置代理一定要重启项目
// 自定义配置H5"h5": {"devServer": {"disableHostCheck": true, // 开启可以用自己的域名-----配置代理一定要重启项目-----配置代理一定要重启项目"proxy": {"/api": {"target": "https://www.zuihuibao.cn","changeOrigin": true,"secure": false,"pathRewrite": {//匹配请求路径里面有 /api 会替换成https://www.zuihuibao.cn// url: `/yiiapp/keduoduo/system/send-sms`, 会被代理带 https://www.zuihuibao.cn/yiiapp/keduoduo/system/send-sms"^/api": ""}}}}}
2.2utils文件的request.js:
注意 :需要根据自己接口的 statusCode 状态码 、数据状态码 return_code 和提示信息 return_message 做对应替换
—需要更改公共地址
—需要注意store的token获取
—需要注意 封装了get post put请求 需要其他的请求自行继续封装
—包含了针对某个特殊接口url 做特殊的错误提示(例如:settings.url.indexOf(‘system/ocr’)>=0)
import store from '../store'let baseUrl = ''
let isExisited = falseconst $https = {}switch (process.env.NODE_ENV) {case 'development':// 公共的地址开发--(为了兼容微信小程序和谷歌浏览器H5 故有以下两个 H5方便浏览器调试)/* #ifdef MP-WEIXIN */baseUrl = 'https://www.zuihuibao.cn/'/* #endif *//* #ifdef H5 */// 修改成如下判断是为了解决 编译H5浏览器跨域问题 同时需要配置manifest.json文件的H5baseUrl = process.env.NODE_ENV === 'development' ? '/api' : 'https://www.zuihuibao.com' // 将否的改成生产环境/* #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('设置cookie', store.getters, headerName, headerValue)// 针对需要token的接口(是否需要看接口传参) 设置获取登录成功后的token 设置在header上settings.header['Cookie'] =`${headerName}=${headerValue}`// 根据是否有token的值 来判断登陆是否有效(需要token 但是缓存没有 就重定向到登录页) 退出时候清除tokenif (!headerValue) {// uni.showModal({// title: '提示',// content: '身份失效,请重新登录!',// 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 查看接口调用是否成功switch (statusCode) {case 200:breakcase 500:// reject({ statusCode: 500, return_message: '服务器重启中...' })uni.showToast({title: data.return_message || '服务器重启中...',duration: 2000,icon: 'none',})returndefault:// reject({ statusCode: statusCode, return_message: '请求失败' })uni.showToast({title: data.return_message || '请求失败,请重试!',duration: 2000,icon: 'none',})return}//在接口200 调用成功后 才能进行判断接口内的状态码 return_code 以此判定作何操作和提示const result = res.dataswitch (result.return_code) {case '0':// 成功的数据data状态码 则直接返回数据// console.log(1111111,result);resolve(result)breakcase '-1004':// 针对识别的接口方法getocr system/ocr做了特殊的错误处理(需要用到这错误修改页面信息)if (settings.url.indexOf('system/ocr')>=0) {// console.log('settings',settings);// console.log('result',result);// 特定接口特定处理-在具体的组件返回的res判断处理resolve(result)} else {// 正常接口报错 继续提示showErrors(result)}breakcase '-1':// 这个是特殊的失败数据 需要接口返回特殊处理resolve(result)breakcase '-1000'://登录失效 清除所有缓存 退到登录页uni.clearStorage()if (hasUserInfo && !isExisited && !checkToken) {isExisited = trueuni.showModal({title: '提示',content: '身份失效,请重新登录!',complete: () => {uni.reLaunch({ url: '/pages/tabBar/login/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: '请求失败,请重试1122!',title: res.return_message || '请求失败,请重试!',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 || '请求失败',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.某个模块的接口请求方法api:
hasToken: false,既不需要token ;
params是url拼接传参;
loading:false,既不存在loading刷新提示(可以通过在api方法内写死,也可以通过vue页面的传参获取动态的);
data是正常传参
/*
// post两种请求 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为{}请求参数,
// params为{},最后更改为url传参
// 默认情况下,接口会传token, 加载框会显示,请求失败信息toast会展示,
// 如需自定义,可以传入opts: {loading: false, hasToken: false, toast: true}
// 其中loading为false, 接口请求时不显示loading框
// hasToken为false, 请求不需要带token
// toast为false,请求失败不会显示系统toast// ```
*/
import { $https } from '../../utils/request'// 根据手机号注册或登录
export function loginByMobile(params,loading) {return $https.post({url: 'yiiapp/keduoduo/system/login-by-mobile',params,hasToken: false,loading:loading == false ? false : true //注意在vue页面传递第二个参数就是loading的值(同理hasToken也可以如此处理)})
}// 根据手机号注册或登录
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,})
}// 提交报价申请
export function submitPriceRecord(params) {return $https.post({url: 'yiiapp/keduoduo/customer/submit-price-record',params,hasToken: true,})
}// 删除车辆
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参数获取
export function getInsurancecompany(params) {return $https.get({url: `api/v1/accident/insurancecompany/list`,params,})
}
// post参数请求
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: {// 使用公众号的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: '获取数据失败',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) {// 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.成功接口请求:
6.失败接口: 404提示:
接口调用成功200 但是data的状态码返回异常 做提示: