Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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,更加明了
}

大佬总结

以上是大佬教程为你收集整理的fetch 从初识到应用全部内容,希望文章能够帮你解决fetch 从初识到应用所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。