handleNullValues方法在封装请求接口返回数据时统一处理
function handleNullValues ( data ) {
function processItem ( item ) {
if ( Array. isArray ( item) ) {
return item. map ( processItem) ;
} else if ( typeof item === 'object' && item !== null ) {
return Object. keys ( item) . reduce ( ( acc, key ) => {
acc[ key] = processItem ( item[ key] ) ;
return acc;
} , { } ) ;
} else if ( item === null ) {
return '' ;
}
return item;
}
return processItem ( data) ;
}
const processedData = handleNullValues ( res. data) ;
resolve ( processedData) ;
全部代码
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 ( ) ;
const token = wx. getStorageSync ( 'token' )
wx. request ( {
url : fullUrl,
method : method,
data : data,
header : {
'content-type' : 'application/x-www-form-urlencoded' ,
'Authorization' : 'Bearer ' + token
} ,
success : ( res ) => {
console. log ( res) ;
if ( res. data. msg === 'success' ) {
hideLoading ( ) ;
function handleNullValues ( data ) {
function processItem ( item ) {
if ( Array. isArray ( item) ) {
return item. map ( processItem) ;
} else if ( typeof item === 'object' && item !== null ) {
return Object. keys ( item) . reduce ( ( acc, key ) => {
acc[ key] = processItem ( item[ key] ) ;
return acc;
} , { } ) ;
} else if ( item === null ) {
return '' ;
}
return item;
}
return processItem ( data) ;
}
const processedData = handleNullValues ( res. data) ;
resolve ( processedData) ;
} else {
hideLoading ( ) ;
wx. showToast ( {
title : res. data. msg,
icon : 'none'
} )
reject ( res. data. msg || '请求失败' ) ;
}
} ,
fail : ( err ) => {
hideLoading ( ) ;
reject ( err. errMsg || '网络请求失败' ) ;
}
} ) ;
} ) ;
}