reactNative 网络工具简单封装
/**
*url :请求地址
*data:参数(Json对象)
*callback:回调函数
*/
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);
}
//定义参数,请求头和请求体
var fetchOptions = {
method: 'POST',
headers: {
'token': this.token
},
body: JSON.stringify(data)
};
//网络请求
fetch(url, fetchOptions)
.then((response) => response.text())
.then((responseText) => {
console.log('3' + responseText)
//回调函数
callback(JSON.parse(responseText));
}).done();
}
}
用这个网络工具写登陆的时候发现总是报错401.
最后挖掘了很久才发现,登陆要用from来提交,后来代码写成了这样