reactNative 網(wǎng)絡(luò)工具簡單封裝
/**
*url :請求地址
*data:參數(shù)(Json對象)
*callback:回調(diào)函數(shù)
*/
static postJson(url, data, callback)
{
var token = '';
var dataJson1 = '';
//取出token
try {
AsyncStorage.getItem(
'token',
(error,result)=>{
if (error){
alert('取值失敗:'+error);
}else{
//alert('取值成功:'+result);
this.token = result
}
}
)
}catch(error){
alert('失敗'+error);
}
//定義參數(shù),請求頭和請求體
var fetchOptions = {
method: 'POST',
headers: {
'token': this.token
},
body: JSON.stringify(data)
};
//網(wǎng)絡(luò)請求
fetch(url, fetchOptions)
.then((response) => response.text())
.then((responseText) => {
console.log('3' + responseText)
//回調(diào)函數(shù)
callback(JSON.parse(responseText));
}).done();
}
}
用這個網(wǎng)絡(luò)工具寫登陸的時候發(fā)現(xiàn)總是報錯401.
最后挖掘了很久才發(fā)現(xiàn),登陸要用from來提交,后來代碼寫成了這樣
Paste_Image.png