react native 網絡請求 axios


react native的網絡請求推薦使用axios和fetch 兩種方式,當前闡述的是axios

1.安裝axios

yarn add react-native-axios

2.創建一個js,進行基本的配置

let instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
withCredentials:true });

baseURL:設置相對應的baseURL來傳遞URL

timeout:設置超時

withCredentials: 允許cookie

Headers:設置頭部信息

method:設置請求方式(常見的有get,post,put,patch,delect)

responseType:設置接受的類型

 

3.攔截器

instance.interceptors.request.use(function (config) {
    const secretKey = getSecretKey()
    if (secretKey) { // 登錄之后 store.getters.token
        config.headers['secret-key'] = secretKey
    } else {
        config.headers['action-key'] = getExternalKey()
    }
    return config
}, function (error) {
    return Promise.reject(error);
});
let  alert = false;
// 響應
instance.interceptors.response.use(response => {
    // 根據狀態碼做相應的事情
    const res = response.data
    if (res.code === 1 && res.showMsg === true) { // 成功
        showToast(res.message,1500);
    }
    if (res.code === -2 && res.showMsg === true) { // 錯誤
        showToast(res.message,3000);
    }
    if (res.code === 2) { // 警告
        showToast(res.message,3000);
    }
    if (res.code === 1003) { //  權限不足 的情況
        showToast('賬號權限不足!',2500);
    }
    if (res.code === 1004 && !alert) { // 獲取不到用戶信息 或 登錄錯誤
        alert = true
        showToast('登錄失敗!',2500);
    }
    console.log(res);
    return res
}, (error) => {
    showToast('出錯了!請稍后再試!',5000);
    return Promise.reject(error);
})

注:在react native IOS版本下無toast,自己手動安裝

yarn add react-native-easy-toast

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM