zoukankan      html  css  js  c++  java
  • fetch和axios区别,摘自Stack Overflow网站答案

    fetch 请求
    let url = 'https://someurl.com'; let options = { method: 'POST', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, body: JSON.stringify({ property_one: value_one, property_two: value_two }) }; let response = await fetch(url, options); let responseOK = response && response.ok; if (responseOK) { let data = await response.json(); // do something with data }

      

    axios请求示例

    let url = 'https://someurl.com';
    let options = {
                method: 'POST',
                url: url,
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                data: {
                    property_one: value_one,
                    property_two: value_two
                }
            };
    let response = await axios(options);
    let responseOK = response && response.status === 200 && response.statusText === 'OK';
    if (responseOK) {
        let data = await response.data;
        // do something with data
    }
    

      原答案:

    • Fetch's body = Axios' data
    • Fetch's body has to be stringified, Axios' data contains the object
    • Fetch has no url in request object, Axios has url in request object
    • Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
    • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
    • To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.

    自己理解答案:

      fetch 中的body是axios的data项

      fetch的请求体必须是字符串,axios是对象

      fetch请求对象不包含URL,axios请求对象包含url

      fetch方法包含url作为参数,axios不用;

      当接收到一个代表错误的 HTTP 状态码时,从 fetch()返回的 Promise 不会被标记为 reject, 即使该 HTTP 响应的状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的 ok 属性设置为 false ), 仅当网络故障时或请求被阻止时,才会标记为 reject。

  • 相关阅读:
    表单提交
    后台返回来的数据是字符串
    背景图充满屏幕
    微信小程序添加模板消息
    axios
    前端常见的跨域解决方案
    gulp的压缩
    git的使用步骤
    vue项目使用mint UI
    利用HBuilder将vue项目打包成移动端app
  • 原文地址:https://www.cnblogs.com/qqfontofweb/p/11316218.html
Copyright © 2011-2022 走看看