js中es6新增请求方法fetch的封装

156 阅读1分钟
function formtor(data) {
    let dataStr = ''
    Object.keys(data).forEach(key => {
       dataStr += key + '=' + data[key] + '&'
    })
    if (dataStr !== '') {
       dataStr = dataStr.substring(0, dataStr.length - 1)
    }
    return dataStr
}

async function ajax(url = '', type = 'GET', data = {}) {
    if (type === "GET") {
       const dataStr = formtor(data)
       url += url + '?' + dataStr
    }
    let requestConfig = {
       method: type,
       headers: {
          "Content-type": "application/x-www-form-urlencoded;charset=UTF-8"
       }

    }
    if (type === "POST") {
       // requestConfig.body = formtor(data)
       //拦截对象,为对象增加新的属性
       //在es6中,我们不推荐直接为一个对象增加新属性的时候使用读取方式
       Object.defineProperties(requestConfig, "body", {
          value: formtor(data)
       })
    }
    const response = await fetch(url, requestConfig)
    const responseJSON = await response.json()
    return responseJSON
}