調用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")
}
},