fetch簡單的封裝與使用

fetch是JavaScript的一個接口,用於進行數據交互,因爲是原生API,性能上更加好。

封裝如下:

const baseUrl = 'http://localhost:3000/';
function ajax(url = '', data = {} , method = "GET"){
    method = method.toUpperCase();
    url = baseUrl + url;
    let config = {
        method:method,
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, same-origin, *omit
        mode: 'cors', // no-cors, cors, *same-origin
        redirect: 'follow', // manual, *follow, error
        referrer: 'no-referrer', // *client, no-referrer
    }
    if(method=="GET"){
        let arr = [];
        for(let key in data){
            arr.push(key + "=" + data[key]);
        }
        url = url + arr.join("&");
    }
    if(['PUT','POST','PATCH'].indexOf(method) != -1){
        config.body=JSON.stringify(data);// must match 'Content-Type' header
        config.headers = {
            'user-agent': 'Mozilla/4.0 MDN Example',
            'content-type': 'application/json'
        }
    }
    return fetch(url, config).then(response => response.json()) 
}

GET:

ajax('login',{name:'zhangsan',password:'123456'}).then((res)=>{
       console.log(res)
 })

POST:

ajax('login',{name:'zhangsan',password:'123456'},"POST").then((res)=>{
     console.log(res)
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章