fetch 從初識到應用

fetch是基於promise進行實現的
對應npm兼容包:node

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

eg:npm

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:json

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包含的經常使用對象:promise

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,更加明瞭
}
相關文章
相關標籤/搜索