公共基础路径封装
module. exports = { BASE_URL : 'https://cloud.chejj.cn' ,
} ;
请求封装
import config from '../config/baseUrl'
const showLoading = ( ) => wx. showLoading ( { title : '加载中...'
} ) ;
const hideLoading = ( ) => wx. hideLoading ( ) ;
export function request ( url, method = 'GET' , data = { } ) { let fullUrl = config. BASE_URL + url; return new Promise ( ( resolve, reject ) => { showLoading ( ) ; wx. request ( { url : fullUrl, method : method, data : data, header : { 'content-type' : 'application/json' , } , success : ( res ) => { if ( res. statusCode === 200 && res. data. success) { hideLoading ( ) ; resolve ( res. data. data) ; } else { hideLoading ( ) ; wx. showToast ( { title : res. data. msg, icon : 'error' } ) reject ( res. data. msg || '请求失败' ) ; } } , fail : ( err ) => { hideLoading ( ) ; reject ( err. errMsg || '网络请求失败' ) ; } } ) ; } ) ;
}
页面使用
async fetchData ( ) { try { const result = await request ( '/mini/default' , 'get' , { } ) ; console. log ( '请求成功,数据为:' , result) ; this . setData ( { data : result} ) ; } catch ( error) { console. error ( '请求失败:' , error) ; } } ,