fetch 从初识到应用

fetch是基于promise进行实现的
对应npm兼容包:

          node-fetch      //兼容node服务的fetch
          iso-whatwg-fetch    //兼容safari中的fetch

eg:

    fetchData(){
        fetch(url, {
            method: 'post',    //这个不用解释了吧
            body: JSON.stringify(data),   //转换为json,要和header对象中的ContentType保持一致
            headers: {
                'Content-Type': 'application/json'   
            },
            credentials: 'include' ,  
            mode: 'cors'
    
        }).then((response) => response.json())
    }

调用对应的fecthData返回一个promise对象
eg:

    fetchData().then((data) => {
          you can do everything on data
     })

以上代码的解释:
credentials: 'include'|‘omit’ | 'same-origin'

   //该值代表request中是否携带cookie到服务器端
   //omit : 默认值,不携带cookie到服务器
   //same-origin:  允许从当前域下携带cookie到服务器端,相对应服务器端的this.set('Access-Control-Allow-Credentials', true)
   //include:  允许携带all-sites下的cookie到服务器端,服务器端要设置相应的Allow-Credentials
mode: 'no-cors' | 'cors'
   //该值代表当前请求是否可以跨域
   //no-cors: 默认值, fetch默认是不跨域的
   //cors: 可以发送跨域请求,相对应服务器端的 this.set('Access-Control-Allow-Origin', this.get('Origin') || '*');

fetch包含的常用对象:

new Request() 
new Response()
new Headers()

这三个对象可以具体应用到fetch中:
将上面的例子可以改写;

fetchData() {
    let header = new Headers({
        'Content-Type': 'application/json'  
        })
    let request = new request({
        method: 'post',    //这个不用解释了吧
        body: JSON.stringify(data),   //转换为json,要和header对象中的ContentType保持一致
        headers: header,   //声明的header对象
        credentials: 'include' ,  
        mode: 'cors'
    })
    fetch(url, request).then((response) => response.json())   //less code,更加明了
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值