当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 浅谈Fetch 数据交互方式

浅谈Fetch 数据交互方式

2019年01月04日  | 移动技术网IT编程  | 我要评论

获取资源很简单,发起一个请求出去,一个响应进来,然后该怎么操作就怎么操作。

fetch 的 api 使用的是 promise 规范,不会 promise(用于延迟(deferred) 计算和异步(asynchronous ) 计算。 一个 promise 对象代表着一个还未完成,但预期将来会完成的操作。主要使用它处理回调黑洞。) 的请花几分钟学习一下。

使用 fetch 去获取数据的方式:

fetch("服务器地址")

  .then(function(response) {

    //将获取到的数据使用 json 转换对象

    return response.json();

  })

  .then(function(data) {

    //获取转换后的格式

    console.log(data);

  })

  //如果有异常会在 catch 捕获

  .catch(function(e) {

    console.log("error");

  }); 

有没有发现使用 fetch 后代码变优美了,不关心数据怎么请求的,把更多的精力放在处理数据上。

不用写回调函数了,也不用监听 xhr readystatechange 事件了,当数据请求回来后会传递给 then, 有异常就会直接触发 catch 事件。

fetch 默认发起的是 get 请求,如果需要 post 请求需要设置 request

request

request 客户端向服务器发出请求的一个对象,包括用户提交的信息以及客户端的一些信息

使用 request 构造一个 fetch 请求的对象的详细信息

//实例化 request 对象
var myrequest = new request(url, option);

fetch(myrequest)
  .then(function(response) {
    console.log(response);
  })
  //如果有异常会在 catch 捕获
  .catch(function(e) {
    console.log("error");
  }); 

request 详细参数配置:

method

设置请求方式

method = get / post / put / delete / head 

headers

设置请求头信息,使用 headers 对象

let headers = new headers({

  'content-type': 'text/plain'

}); 

mode

请求的模式,主要用于跨域设置

mode = cors / no-cors / same-origin

cors : 跨域

no-cors : 不跨域

same-origin : 同源

credentials

需要向服务器发送 cookie 时设置

credentials = omit / same-origin

 omit : 省略

same-origin : 发送同源 cookie

cache

cache = default / reload / no-cache

redirect

收到重定向消息时如何处理

redirect = follow / error / manual

follow : 跟随重定向的地址 ,继续请求

error : 不请求

比如:

var request = new request("url", {

    headers: new headers({

      "content-type": "text/plain"

    }),

    method : "post",

    mode: "cors",

    redirect : "follow"

  });

fetch(request)

  .then((response) => {

    console.log(response);

  })

  .catch((error)=>{

    console.log(error);

  }); 

fetch 数据处理

当 fetch 把请求结果拿到后,我们需要使用它提供的几个方法来做处理

json 

fetch 提供了一个 json 方法将数据转换为 json 格式

fetch(url)

  .then((response) => {

    //返回 object 类型

    return response.json();

  })

  .then((result) => {

    console.log(result);

  }); 

text

fetch 提供了一个 text 方法用于获取数据,返回的是 string 格式数据

fetch(url)

  .then((response) => {

    //返回 string 类型

    return response.text();

  })

  .then((result) => {

    console.log(result);

  });   

blob

如果我们获取的是一个图像,需要先设置头信息,然后 fetch 会正常处理本次请求,最终使用 blob 方法获取本次请求的结果, 可以把结果赋值给 img src 就能正常的显示一张图片

var request = new request("xx.img", {

    headers: new headers({

      "content-type": "image/jpeg"

    }),

    method : "get",

    cache: 'default'

  });

fetch(request)

  .then((response) => {

    return response.blob();

  })

  .then((stories)=>{

    var objecturl = url.createobjecturl(stories);

    let img = document.createelement("img");

    img.src = objecturl;

    document.queryselector("body").appendchild(img);

  }); 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网