@2890594972
2018-05-23T09:09:37.000000Z
字数 1082
阅读 777
react
react教学
fetch(url);//返回的是一个Promise对象,有then以及catch方法,then中就是成功回调得到的数据地方,catch就是数据请求失败或者出现其他异常情况,从而得到这个error的地方。
fetch('url').then((res) => {
console.log(res);
}).catch(err=>{
console.log(err);
})
fetch(url,opt).then(res=>{
console.log(res);
})
fetch('https://mywebsites.com/json',{
methods:"GET",
headers: {
"Content-Type":"application/json"
},
data: {
userName:'mapbar',
password:12345
}
})
fetch(url,opt).then(res=>{
console.log(res);
})
fetch('https://mywebsites.com/json',{
methods:"GET",
headers: {
"Content-Type":"application/json"
},
body: JSON.stringify({
userName:'mapbar',
password:12345
})
});
//如果你要上传图片、file文件
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'key1=value1&key2=value2'
})
其他情况下,一般用application/json.
//实例
<script src="https://cdn.bootcss.com/fetch/2.0.3/fetch.min.js"></script>
fetch('https://w.mapbar.com/search2015/search?keywords=北京').then(res=>{
return res.json();
}).then(data => {
console.log(data);
})