[关闭]
@2890594972 2018-05-23T09:09:37.000000Z 字数 1082 阅读 777

react fetch(三)

react react教学


react fetch

1、最简单的fetch

fetch(url);//返回的是一个Promise对象,有then以及catch方法,then中就是成功回调得到的数据地方,catch就是数据请求失败或者出现其他异常情况,从而得到这个error的地方。

  1. fetch('url').then((res) => {
  2. console.log(res);
  3. }).catch(err=>{
  4. console.log(err);
  5. })

2、get方式的fetch。

  1. fetch(url,opt).then(res=>{
  2. console.log(res);
  3. })
  4. fetch('https://mywebsites.com/json',{
  5. methods:"GET",
  6. headers: {
  7. "Content-Type":"application/json"
  8. },
  9. data: {
  10. userName:'mapbar'
  11. password:12345
  12. }
  13. })

3、post方式的fetch

  1. fetch(url,opt).then(res=>{
  2. console.log(res);
  3. })
  4. fetch('https://mywebsites.com/json',{
  5. methods:"GET",
  6. headers: {
  7. "Content-Type":"application/json"
  8. },
  9. body: JSON.stringify({
  10. userName:'mapbar'
  11. password:12345
  12. })
  13. });
  14. //如果你要上传图片、file文件
  15. fetch('https://mywebsite.com/endpoint/', {
  16. method: 'POST',
  17. headers: {
  18. 'Content-Type': 'application/x-www-form-urlencoded',
  19. },
  20. body: 'key1=value1&key2=value2'
  21. })

Content-Type:上传文件的时候,一定要设置为application/x-www-form-urlencoded

其他情况下,一般用application/json.

  1. //实例
  2. <script src="https://cdn.bootcss.com/fetch/2.0.3/fetch.min.js"></script>
  3. fetch('https://w.mapbar.com/search2015/search?keywords=北京').then(res=>{
  4. return res.json();
  5. }).then(data => {
  6. console.log(data);
  7. })
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注