fetch 处理网络请求

落日映苍穹つ 2021-07-24 11:35 499阅读 0赞
  1. (1)基本使用
  2. get请求
  3. fetch('路径')
  4. //返回响应对象,并要求为json格式
  5. .then(data=>{return data.json()}) data.ok返回是否成功,可改写成if(data.ok){return data.json()}
  6. //返回真实数据
  7. .then(res=>{xxx})
  8. 使用asyncawait语法糖
  9. fetch('路径').then(async (res)=>{
  10. if(res.ok){
  11. let data=await res.json()
  12. }
  13. })
  14. post请求
  15. fetch('路径',{
  16. method:'POST',
  17. //设置请求头
  18. headers:{
  19. 'Accept': 'application/json, text/plain, */*',
  20. 'Content-Type': 'application/x-www-form-urlencoded'
  21. },
  22. body:"传入的键值对参数,以&分割" 或使用qs.stringify(对象),import qs from "qs"
  23. }).then(data=>{return data.json()})
  24. .then(res=>{xxx})
  25. (2)中断请求
  26. const controller = new AbortController()
  27. const signal = controller.signal
  28. fetch('/todos', {
  29. method: 'get',
  30. signal,
  31. })
  32. 中断:controller.abort()
  33. (3)将对象的内容,转成url参数形式
  34. function fun(obj)
  35. {
  36. var res='';
  37. for(var key in obj)
  38. {
  39. res+='&'+key+'='+encodeURIComponent(obj[key]);
  40. }
  41. if(result)
  42. {
  43. //去掉开头的'&'
  44. res=res.slice(1);
  45. }
  46. return res;
  47. }

代码示例:

  1. import qs from "qs"
  2. var flag=false;
  3. if(flag)
  4. {
  5. //get请求
  6. fetch('http://localhost:3000/news')
  7. .then(data=>{ return data.json()})
  8. .then(res=>{ console.log(res)})
  9. }else{
  10. //post请求
  11. fetch('http://localhost:3000/news',{
  12. method:'POST',
  13. headers:{
  14. 'Accept': 'application/json, text/plain, */*',
  15. 'Content-Type': 'application/x-www-form-urlencoded'
  16. },
  17. body:"id=jeff"
  18. }).then(data=>{ return data.json()})
  19. .then(res=>{ console.log(res)})
  20. }
  21. export function getData(url) {
  22. const result = fetch(url);
  23. return result;
  24. }
  25. export function postData(url,data) {
  26. const result = fetch(url, {
  27. method: "post",
  28. headers: {
  29. 'Accept': 'application/json, text/plain, */*',
  30. 'Content-Type': 'application/x-www-form-urlencoded'
  31. },
  32. body:qs.stringify(data)
  33. })
  34. console.log(qs.stringify(data));
  35. return result;
  36. }

发表评论

表情:
评论列表 (有 0 条评论,499人围观)

还没有评论,来说两句吧...

相关阅读

    相关 fetch请求详解

    最新更新时间:2019年06月04日16:18:30 [`《猛戳-查看我的博客地图-总有你意想不到的惊喜》`][-_-] > 本文内容:fetch相关 概述