阅读 552

使用 fetch 封装网络请求,返回promise 对象

地址:www.cnblogs.com/canghaiyime…

fetch基本用法

// 封装get请求
export function httpGet(url){
    var result = fetch(url)
    return result
}
// 封装post请求
export function httpPost(url,data){
    var result = fetch(url,{
        method:'post',
        headers:{
            'Accept':'application/json,text/plain,*/*',/* 格式限制:json、文本、其他格式 */
            'Content-Type':'application/x-www-form-urlencoded'/* 请求内容类型 */
        },
        //data表单数据,body最终要的格式为username=tony&pwd=123456,所以需要格式化
        body: JSON.stringify(data)
    })
    return result
}
复制代码

下面是使用Promise 封装了Fetch 并返回promise 对象

const headers = new Headers({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
});

function get (url) {
  return fetch(url, {
    method: 'GET',
    headers: headers
  }).then(response => {
    return handleResponse(url, response);
  }).catch(err => {
    console.error(`Request failed. Url = ${url} . Message = ${err}`);
    return {error: {message: 'Request failed.'}};
  })
}

function post (url, data) {
  return fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
  }).then(response => {
    return handleResponse(url, response);
  }).catch(err => {
    console.error(`Request failed. Url = ${url} . Message = ${err}`);
    return {error: {message: 'Request failed.'}};
  })
}

function put (url, data) {
  return fetch(url, {
    method: 'PUT',
    headers: headers,
    body: JSON.stringify(data)
  }).then(response => {
    return handleResponse(url, response);
  }).catch(err => {
    console.error(`Request failed. Url = ${url} . Message = ${err}`);
    return {error: {message: 'Request failed.'}};
  })
}

function handleResponse (url, response) {
  if (response.status < 500) {
    return response.json();
  } else {
    console.error(`Request failed. Url = ${url} . Message = ${response.statusText}`);
    return {error: {message: 'Request failed due to server error '}};
  }
}

export {get, post, put}
复制代码