调用react-native-fs插件时,如果数据的接口是需要验证信息的,在android上运行报错,而在iOS上运行没问题。原因是因为接口是有验证信息的,而调用这个插件时没有传入,在iOS上会自动加上验证信息,而 android需要手动设置。
此错误的解决方法:
1.在调用登录接口时,保存下cookie(cookie在response里),在调用react-native-fs时放在headers里传入,代码如下:
_appLogin(userName, password, callback){ fetch(commonSvc.baseURL + '/account/app-login', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ UserName: userName, Password: password }) }).then( (response) => { if (response.ok) { return response; } else { var message; switch (response.status) { case 710: message = LanguageChooseSvc.strings['api_common_' + 710]; break; case 711: message = LanguageChooseSvc.strings['api_common_' + 711]; break; case 400: message = LanguageChooseSvc.strings['api_common_' + 400]; break; default: message = commonSvc.httpErrorMessage; break; } throw {message: message}; } } ).then( (responseJson) => { callback(null, responseJson); } ).catch( (error) => { callback(error.message); } ); },
2.在调用react-native-fs时放在headers里传入,代码如下:
downloadFile(imageId, cookie, callback) {
const downloadDest = `${RNFS.DocumentDirectoryPath}/${((Math.random() * 1000) | 0)}.jpg`;
var formUrl = CommonSvc.baseURL + '/api/image/0/' + imageId;
//var formUrl = 'http://lorempixel.com/400/200/';
const options = {
fromUrl: formUrl,
toFile: downloadDest,
background: true,
headers: {
'Cookie': cookie //需要添加验证到接口要设置cookie
},
begin: (res) => {
//console.log(res);
},
progress: (res) => {
//console.log(res);
}
};
try {
const ret = RNFS.downloadFile(options);
ret.promise.then(res => {
//callback(null, Platform.OS === 'android' ? downloadDest : 'file://' + downloadDest)
callback(null, 'file://' + downloadDest)
}).catch(err => {
callback(err)
});
}
catch (e) {
callback("error")
}
},