fetch是基于promise,fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。

fetch

特点
1、第一个参数是URL:
2、第二个是可选参数,可以控制不同配置的 init 对象
3、使用了 JavaScript Promises 来处理结果/回调:

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});

使用箭头函数:

fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

获取一个JSON文件,并打印到控制台。指明资源路径,然后返回一个Response对象,使用json()方法获取JSON但内容。

处理status和返回结果:

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })

以上会存在数据返回异常的情况(请求异常,服务器没有抛出错误):

ajax.js:165 Uncaught (in promise) TypeError: response.joson is not a function
    at parseJSON (ajax.js:165)

 

对服务器异常处理:

// 封装fetch请求
export function httpPost(uri, params) {
    if (!isLogin()) {
        window.location.hash = '#/login';
    };
    let headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    };
    headers.token = window.localStorage.getItem('accessToken') || '';
    let init = {
        method: 'POST',
        credentials: 'include',
        headers: headers,
        body: JSON.stringify(params)
    };
    if (DEBUG) {
        uri = CTX + uri;
        init.mode = 'cors';
    }
    return new Promise(function (resolve, reject) {
        fetch(uri, init)
            .then(checkStatus)
            .then(parseJSON)
            .then(data => {
                console.log(data);
                if (!data) return;
                if (data.status === 0) {
                    resolve(data.data);
                } else {
                    processError(data);
                }
            }).catch(function (ex) {
                reject(ex, '服务器错误');
            });
    });
}

// 处理请求状态status
function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response
    } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
    }
}

// 处理请求结果response
function parseJSON(response) {
    return response.json().then((res) => {
        return new Promise((resolve, reject) => {
            resolve(res);
        })
    }).catch(err => {
        console.log(err,'服务器返回错误');
    });
}

 

GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2134cb94 * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance * fix ci_static_analysis_clang (ci_clang_tidy) * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance 8 天前
6057b31d * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * Use ubuntu-latest image to run Valgrind (#4575) * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Ubuntu image to run valgrind * Use Clang image to run iwyu (#4574) * :wrench: use Clang image to run iwyu * :wrench: use Clang image to run iwyu * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :art: format code * :hammer: clean up 10 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐