fetch是基于promise实现的对应的npm兼容包:node-fetch//兼容节点服务fetchis-whatwg-fetch//兼容safari中的fetcheg: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)=>{你可以在数据上做任何事情})上面代码的解释:credentials:'include'|'omit'|'same-origin'//该值表示请求是否携带cookie到服务器//omit:默认值,不携带cookie到服务器//same-origin:允许携带cookie从当前域到服务器server,对应server端的this.set('Access-Control-Allow-Credentials',true)//include:Allowstocarrycookiesunderall-sitesto在server端,要设置对应的Allow-Credentialsmode服务器端:'no-cors'|'cors'//这个值表示当前请求是否可以跨域//no-cors:默认值,fetch默认不跨域//cors:可以发送跨域请求,对应this.set('Access-Control-Allow-Origin',this.get('Origin')||'*');服务器端fetch包含的常见对象:newRequest()newResponse()newHeaders()这三个对象可以具体应用于fetch:上面的例子可以重写;fetchData(){letheader=newHeaders({'Content-Type':'application/json'})letrequest=newrequest({method:'post',//这个body:JSON.stringify(data),//转成json,保持ContentType与header对象一致headers:header,//声明的header对象credentials:'include',mode:'cors'})fetch(url,request).then((response)=>response.json())//代码更少,更清晰}
