Skip to content

Commit

Permalink
request按需引入
Browse files Browse the repository at this point in the history
jry committed Apr 7, 2024
1 parent caad604 commit 1e75627
Showing 2 changed files with 14 additions and 11 deletions.
10 changes: 6 additions & 4 deletions src/util/request/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// 引入配置
// 引入配置
import config from '@/common/config'
// 引入拦截器配置
import {requestInterceptors,responseInterceptors} from './interceptors.js'
import {requestInterceptors,responseInterceptors} from './interceptors.js'
// 引入luch-request
import { http } from '@/uni_modules/uview-plus'
// 初始化请求配置
const initRequest=(vm)=>{
uni.$u.http.setConfig((defaultConfig) => {
http.setConfig((defaultConfig) => {
/* defaultConfig 为默认全局配置 */
defaultConfig.baseURL = config.baseUrl /* 根域名 */
return defaultConfig
@@ -13,7 +15,7 @@ const initRequest=(vm)=>{
responseInterceptors()
}
export {
initRequest
initRequest
}


15 changes: 8 additions & 7 deletions src/util/request/interceptors.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { http, toast} from '@/uni_modules/uview-plus'
const requestInterceptors=(vm)=>{
/**
* 请求拦截
* @param {Object} http
*/
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
debugger
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
alert()
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
config.data = config.data || {}
// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
@@ -18,14 +19,14 @@ const responseInterceptors=(vm)=>{
* 响应拦截
* @param {Object} http
*/
uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
const data = response.data
// 自定义参数
const custom = response.config?.custom
if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
if (custom.toast !== false) {
uni.$u.toast(data.message)
toast(data.message)
}
// 如果需要catch返回,则进行reject
if (custom?.catch) {
@@ -42,9 +43,9 @@ const responseInterceptors=(vm)=>{
}


export {
export {
requestInterceptors,
responseInterceptors
responseInterceptors
}



0 comments on commit 1e75627

Please sign in to comment.