fetch手写、ajax手写、一些知识跨域

1,330 阅读1分钟

fetch

function http(url,optioins={}){
    let{
    method='get',
    data={},
    headers={},
    credentials='same-origin'
    }=options
    let isGet = method.toLowerCase() == 'get';
    if(isGet){
        //若是get请求,则需要我们把data中的参数补成url后边的search字符串
        let str = '';
        for(let k in data){
            str += `${k}=${data[k]}&` // get后边补&,但是最后一个会多一个&
        }
        str = str.replace(/&$/,'') // 把最后一个&替换成空
        url = url.indexOf('?') == -1 ? url + '?' + str : url + '&' + str
        //看url是否带? 没带的话补一个,带的话直接拼search字符串
    }
    return fetch(url,{
        method:method,
        body: isGet ? null : JSON.stringify(data)
        headers,  //全写  headers:headers
        credentials
    }).then((data)=>{
        if(/[45]\d{2}/.test(data.status)){
            throw Error(`${data.status}${data.statusText}`)
        }
        return data.json();
    })
}
http.get = function(url,data){
    return http(url,{
        method:'get',
        data
    })
}
http.post = function(url,data){
    return http(url,{
        method:'post',
        data
    })
}

ajax

function ajax(url,options={}){
    let{
        method = 'get',
        async = 'true', //是否异步  true 是异步
        data = {},
        cache='true', // 是否走缓存  true走缓存
        headers = {}
    }=options
    let isGet = method.toLowerCase() == 'get'; //判断是否为get
    let searchStr = '';
    for(let k in data){
        searchStr += `&${k}=${data[k]}`  //给前面补&,最前面会多一个&
    }
    searchStr = searchStr.slice(1) //从第一个字符串开始截,即跳过多出的&
    if(isGet){
        url = url.indexOf('?') == -1 ? url + '?' + searchStr : url + '&' + searchStr;
    }
    return new Promise(function(res,rej){
        let xhr = new XMLHttpRequest
        xhr.open(method,url,async)
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 ){
                if(/2\d{2}|304/.test(xhr.status)){
                    let data = JSON.parse(xhr.response)
                    res(data)
                }else if(/[45]\d{2}/.test(xhr.status)){
                    rej(xhr)
                }
            }
        }
        xhr.send(JSON.stringify(data))
    })
}
ajax.get = function(url,data){
    return ajax(url,{
        method:'get',
        data
    })
}
ajax.post = function(url,data){
    return ajax(url,{
        method:'post',
        data
    })
}

###跨域 跨域:浏览器的保护机制 - 协议 - 域名 - 端口 三者必须保持一致,只要有一个不同就是跨域

ajax 请求时 会遇到跨域问题 link script img ... 这些标签没有跨域

解决跨域的几种方式: json: 利用script标签的src不存在跨域这个特性实现的 cors: 让后台配置 Access-Control-Allow-Origin // 若是post的复杂数据类型传递(JSON),浏览器会默认发送一个POTIONS请求,就是问你后台支不支持跨域 proxy: 找了个本地代理(中介,中介商)

tragetWindow.postMessage  onmessage