uni-app开发钉钉小程序 uni.request方法 fail回调 在ios手机上 拿不到后端返回的data数据

uni-app开发钉钉小程序 uni.request方法 fail回调 在ios手机上 拿不到后端返回的data数据

信息类别 详情
产品分类 uniapp/小程序
开发环境 Mac
操作系统版本 13.2.1
HBuilderX类型 正式
HBuilderX版本 3.5.3
第三方开发者工具版本 3.9.22
基础库版本 2.0.2
项目创建方式 HBuilderX

示例代码:

fail: function(err) {  
    uni.hideLoading();  
    // #ifdef MP-ALIPAY  
    if (err.statusCode === 200) {  
        // uni.showToast({  
        //  title: err.data,  
        //  icon: "none"  
        // });  
        if (params.callBack) {  
            params.callBack(err.data);  
        }  
        return  
    } else if (err.statusCode === 400) {  
        if (params.errCallBack) {  
            uni.hideLoading();  
            params.errCallBack(err);  
            return  
        } else {  
            setTimeout(() => {  
                uni.showToast({  
                    title: err.data||'出错了',  
                    icon: "none"  
                });  
            }, 1);  
        }  
    } else if (err.statusCode === 401 && bool) {  
        refauchToken(params)  
    } else if (typeof err.data === 'string' && err.statusCode === 475) { //登录475  
        return  
    } else if (err.statusCode !== 200 && err.statusCode !== 401) {  
        uni.showToast({  
            title: err.data,  
            icon: "none"  
        });  
    }  
    // #endif  
    if (err.errMsg == 'request:fail abort') {  
        console.log('请求被取消啦~')  
        return  
    }  
    // #ifndef MP-ALIPAY  
    setTimeout(() => {  
        uni.showToast({  
            title: i18n.t('index.serverWrong'),  
            icon: "none"  
        });  
    }, 1);  
    // #endif  
}

操作步骤:

接口400的时候,走了fail 回调,但是在ios 上拿不到后端抛出得data信息,但是在安卓上是可以

预期结果:

在ios上应该也能拿到错误信息

实际结果:

ios上是拿不到错误信息

bug描述:

开发钉钉小程序, uni.request方法,fail回调,在ios手机上,拿不到后端返回的data数据


更多关于uni-app开发钉钉小程序 uni.request方法 fail回调 在ios手机上 拿不到后端返回的data数据的实战教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复

这个反馈比较少,安卓没问题?ios 真机一定有问题? 自己写一个空白工程,用原生方案写一个 request 试试吧。如果原生没问题,提供一个可运行的工程

更多关于uni-app开发钉钉小程序 uni.request方法 fail回调 在ios手机上 拿不到后端返回的data数据的实战教程也可以访问 https://www.itying.com/category-93-b0.html


对的,安卓没有问题,iOS上就有问题,我这是uniapp项目打包成钉钉小程序

回复 9***@qq.com: 看下你的完整请求,发一个单页面源码给我

回复 DCloud_UNI_OttoJi: 我通过什么形式发给你

回复 DCloud_UNI_OttoJi: 代码我贴下面给你了

var config = require("./config.js"); //统一的网络请求方法
var util = require("./util.js")
var router = require(’…/router/index.js’)
var timer = ‘’
let bool = true
import moment from ‘dayjs’
import {
AppType
} from ‘./constant.js’

import i18n from ‘…/main.js’

function request(params) {
// 全局变量
var globalData = getApp().globalData; // 如果正在进行登陆,就将非登陆请求放在队列中等待登陆完毕后进行调用
// 刷新token
if (!params.login && !globalData.isLanding && !params.isRefreshing) {
params = util.refreshToken(params)
}
const appType = uni.getStorageSync(‘appType’)
if ((appType === AppType.MP || appType === AppType.MINI) &&
!params.login && globalData.isLanding && !params.isRefreshing) {
globalData.requestQueue.push(params);
return
}
if (Object.prototype.toString.call(params.data) == ‘[object Array]’) {
params.data = JSON.stringify(params.data);
} else if (Object.prototype.toString.call(params.data) == ‘[object Number]’) {
params.data = params.data + ‘’;
}
uni.request({
url: (params.domain ? params.domain : config.domain) + params.url,
//接口请求地址
data: params.data,
timeout: 10000,
header: {
‘content-type’: params.method == “GET” ? ‘application/x-www-form-urlencoded’ :
‘application/json;charset=utf-8’,
‘Authorization’: uni.getStorageSync(‘token’),
‘locale’: uni.getStorageSync(‘lang’) || ‘zh_CN’,
‘traceId’:moment().valueOf()+Math.random().toString(36).substring(2),
// #ifndef MP-ALIPAY
‘appId’: config.mpAppId || ‘’,
‘platformAppId’:config.mpAppId||’’,
// #endif
// #ifdef MP-ALIPAY
‘platformAppId’:config.clientId||’’,
‘appId’: config.clientId||’’,
// #endif
},
method: params.method||‘POST’,
dataType: params.dataType ? params.dataType : ‘json’,
// #ifndef MP-ALIPAY
responseType: params.responseType == undefined ? ‘text’ : params.responseType,
// #endif
success: function (res) {
if (res.statusCode == 200) {
//如果有定义了params.callBack,则调用 params.callBack(res.data)
if (res.data && (res.data.code === 400||res.data.code===‘8500’)) {
uni.hideLoading()
setTimeout(() => {
uni.showToast({
title: res.data.msg,
icon: “none”
});
}, 1);
}
else if (params.callBack) {
params.callBack(res.data);
}
} else if (res.statusCode == 500) {
uni.hideLoading()
setTimeout(() => {
uni.showToast({
title: i18n.t(‘index.serverWrong’),
icon: “none”
});
}, 1);
} else if (res.statusCode == 401) {
if (!timer && bool) {
refauchToken(params)
timer = 1
}
} else if (res.statusCode == 400 && !params.errCallBack) {
uni.hideLoading();
setTimeout(() => {
uni.showToast({
title: res.data,
icon: “none”
});
}, 1);
} else {
//如果有定义了params.errCallBack,则调用 params.errCallBack(res.data)
uni.hideLoading();
if (params.errCallBack) {
params.errCallBack(res);
}
}
},
fail: function(err) {
uni.hideLoading();
// #ifdef MP-ALIPAY
if (err.statusCode === 200) {
// uni.showToast({
// title: err.data,
// icon: “none”
// });
if (params.callBack) {
params.callBack(err.data);
}
return
} else if (err.statusCode === 400) {
if (params.errCallBack) {
uni.hideLoading();
params.errCallBack(err);
return
} else {
setTimeout(() => {
uni.showToast({
title: err.data||‘出错了’,
icon: “none”
});
}, 1);
}
} else if (err.statusCode === 401 && bool) {
refauchToken(params)
} else if (typeof err.data === ‘string’ && err.statusCode === 475) { //登录475
return
} else if (err.statusCode !== 200 && err.statusCode !== 401) {
uni.showToast({
title: err.data,
icon: “none”
});
}
// #endif
if (err.errMsg == ‘request:fail abort’) {
console.log(‘请求被取消啦~’)
return
}
// #ifndef MP-ALIPAY
setTimeout(() => {
uni.showToast({
title: i18n.t(‘index.serverWrong’),
icon: “none”
});
}, 1);
// #endif
}
});
}

// 处理登录失效,或者禁用刷新token
function refauchToken(params) {
setTimeout(() => {
timer = ‘’
}, 2000)
bool = false
uni.removeStorageSync(‘loginResult’);
uni.removeStorageSync(‘token’);
uni.removeStorageSync(‘hadBindUser’);
uni.removeStorageSync(‘code’);
uni.removeStorageSync(‘userInfo’);
uni.removeStorageSync(‘expiresTimeStamp’);
// #ifdef H5
const ua = navigator.userAgent.toLowerCase();
if (ua.search(/MicroMessenger/i) > -1) uni.setStorageSync(‘appType’, AppType.MP)
// #endif
uni.hideLoading();
const pages = getCurrentPages()
uni.setStorageSync(‘routeUrlAfterLogin’, pages.length ? pages[pages.length - 1].$page.fullPath :
‘/pages/index/index’)
if (!params.dontTrunLogin) {
if (uni.getStorageSync(‘hadLogin’)) {
uni.showModal({
title: i18n.t(‘index.tips’),
content: i18n.t(‘index.loginExpired’),
cancelText: i18n.t(‘index.cancel’),
confirmText: i18n.t(‘index.confirm’),
success: res => {
bool = true
if (res.confirm) {
uni.navigateTo({
url: ‘/pagesA/login/login’
})
return
} else {
let router = getCurrentPages()
if (router[0].route === ‘pages/basket/basket’) {
uni.switchTab({
url: ‘/pages/index/index’
})
} else {
uni.navigateBack(0)
}
}
},
fail: () => {
bool = true
}
})
} else {
// #ifdef MP-WEIXIN || MP-ALIPAY
uni.navigateTo({
url: ‘/pagesA/login/login’
})
// #endif
}
}
// 如果有定义了params.errCallBack,则调用 params.errCallBack(res.data)
if (params.errCallBack) {
params.errCallBack(res);
} else {
// #ifdef MP-ALIPAY
util.DDLogin()
// #endif
// #ifndef MP-ALIPAY
// util.weChatLogin()
// #endif
}
}
/**

  • 上传文件统一接口
    */
    function upload(params) {
    uni.uploadFile({
    url: config.domain + params.url,
    filePath: params.filePath,
    fileType: ‘image’,
    name: params.name,
    header: {
    ‘Authorization’: params.login ? undefined : uni.getStorageSync(‘token’)
    },
    dataType: ‘json’,
    responseType: params.responseType == undefined ? ‘json’ : params.responseType,
    success: function(res) {
    if (res.statusCode == 200) {
    //如果有定义了params.callBack,则调用 params.callBack(res.data)
    if (params.callBack) {
    params.callBack(res.data);
    }
    } else {
    uni.showToast({
    title: i18n.t(‘index.serverWrong’),
    icon: “none”
    });
    }
    },
    fail: function(err) {
    console.log(err)
    uni.hideLoading();
    }
    });
    }

var getToken = function(fn) {

};

// 更新用户头像昵称
function updateUserInfo() {
// wx.getUserInfo({
// success: res => {
// console.log(res)
// var userInfo = JSON.parse(res.rawData);
// uni.setStorageSync(‘userInfo’, JSON.parse(res.rawData))
// request({
// url: “/p/user/setUserInfo”,
// method: “POST”,
// data: {
// avatarUrl: userInfo.avatarUrl,
// nickName: userInfo.nickName
// }
// });
// }
// });
}

/**

  • 获取购物车商品数量
    */
    function getCartCount() {
    if (!wx.getStorageSync(‘token’)) {
    util.removeTabBadge()
    return
    }
    var params = {
    url: “/p/shopCart/prodCount”,
    method: “GET”,
    dontTrunLogin: true,
    data: {},
    callBack: function(res) {
    if (res > 0) {
    wx.setTabBarBadge({
    index: 2,
    text: res > 99 ? “99+” : res + “”
    });
    var app = getApp().globalData;
    getApp().globalData.totalCartCount = res;
    } else {
    util.removeTabBadge()
    var app = getApp().globalData;
    getApp().globalData.totalCartCount = 0;
    }
    }
    };
    request(params);
    }

function isUserAuthInfo() {
// 查看是否授权
wx.getSetting({
success(res) {
if (res.authSetting[‘scope.userInfo’]) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称
wx.getUserInfo({
success: function(res) {
console.log(res.userInfo);
}
});
}
}
});
}

function mpAuthLogin(page, needCode) {
// 在微信环境打开,请求公众号网页登陆
var redirectUrl = null

if (!page || page === config.domainAddress) {  
    redirectUrl = window.location.href  
} else {  
    redirectUrl = config.domainAddress + page  
}  
var scope = 'snsapi_userinfo'  
window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.mpAppId +  
    '&redirect_uri=' +  
    encodeURIComponent(redirectUrl) + '&response_type=code&scope=' + scope + '&state=' + (needCode ? 'needCode' :  
        'unNeedCode') +  
    '#wechat_redirect'  

}

/**

  • 用户操作记录
  • visitType 访问类型 1:页面访问 2:分享访问 3:页面点击 4:加入购物车"
    */
    var saveLog = function(flowData, visitType) {
    var flowAnalysisLogDto = Object.assign(flowData)
    flowAnalysisLogDto.visitType = visitType
    var params = {
    url: ‘/flowAnalysisLog’,
    method: ‘POST’,
    data: flowAnalysisLogDto,
    callBack: () => {
    // console.log(params.data)
    }
    }
    request(params)
    }

exports.getToken = getToken;
exports.request = request;
exports.getCartCount = getCartCount;
exports.updateUserInfo = updateUserInfo;
exports.upload = upload;
exports.mpAuthLogin = mpAuthLogin;
exports.saveLog = saveLog;

这是一个钉钉小程序在iOS平台上的兼容性问题。在uni.request的fail回调中,iOS设备可能无法正确解析后端返回的错误数据。

问题分析:

  1. iOS平台的钉钉小程序可能对fail回调的数据结构处理与Android不同
  2. 错误数据可能被封装在err对象的不同属性中

解决方案建议:

  1. 尝试使用err.response或err.responseData来获取错误数据
  2. 检查err对象的完整结构,在fail回调中添加console.log(err)查看完整错误对象
  3. 确保后端返回的错误数据是标准JSON格式

修改后的代码示例:

fail: function(err) {
    console.log('完整错误对象:', err); // 调试用
    uni.hideLoading();
    let errorData = err.data || err.response || err.responseData;
    
    // 处理错误逻辑...
    if(errorData) {
        // 使用errorData代替原来的err.data
    }
}
回到顶部