zoukankan      html  css  js  c++  java
  • Xhr

    xhr Learning 续

    2、Axios

    Axios文档

    • 定义:Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中
    • 安装:$ npm install axios
    • 引入: import axios from 'axios'
      cdn: https://unpkg.com/axios/dist/axios.min.js

    使用
    1)get请求

    1
    2
    3
    4
    5
    6
    7
    axios.get('/api/articles?type=more&category=home&shown_offset=1540351013034122&first_view=false')
    .then(function(res){
    console.log(res)
    })
    .catch(function(error){
    console.log(error)
    })

    2)post请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    axios.post('/api/v4/articles/45395824/voters',{
    params:{
    voting:1
    }
    })
    .then(function(res){
    console.log(res)
    })
    .catch(function(error){
    console.log(error)
    })

    3)执行多个并发请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function  (){
    return axios.get('/api/articles?type=more&category=home&shown_offset=1540351013034122&first_view=false')
    }
    function getCareerArticle(){
    return axios.get('/api/articles?type=more&category=career&shown_offset=1540450144315916')
    }
    axios.all([getHomeArticle(),getCareerArticle()])
    .then(axios.spread(function(home,career){
    console.log(home)
    console.log(career)
    }))

    axios.all(iterable) axios.spread(callback)

    4)axios(url[, config])

    1
    2
    3
    4
    5
    6
    7
    8
    axios({
    method: 'post',
    url: '/user/12345',
    data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
    }
    });

    ——请求方法的别名

    axios.request(config)
    axios.get(url[, config])
    axios.delete(url[, config])
    axios.head(url[, config])
    axios.post(url[, data[, config]])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])

    在使用别名方法时, urlmethoddata 这些属性都不必在配置中指定
    若想指定其他参数,可以使用实例方法如:axios#post(url[, data[, config]])

    5)响应结构

    1
    2
    3
    4
    5
    6
    7
    {
    data: {},
    status: 200, // `status` 来自服务器响应的 HTTP 状态码
    statusText: 'OK', // `statusText` 来自服务器响应的 HTTP 状态信息
    headers: {}, // `headers` 服务器响应的头
    config: {} // `config` 是为请求提供的配置信息
    }

    6)配置的默认值/defaults

    1
    2
    axios.defaults.baseURL = 'https://api.example.com';
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

    配置的优先顺序:库的默认值 < 实例的 defaults 属性 < 请求的 config 参数

    7)错误处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    axios.get('/user/12345')
    .catch(大专栏  Xhrn class="keyword">function (error) {
    if (error.response) {
    // 请求已发出,但服务器响应的状态码不在 2xx 范围内
    console.log(error.response)
    } else {
    // Something happened in setting up the request that triggered an Error
    console.log('Error', error.message);
    }
    console.log(error.config);
    });

    • 可以使用 validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围

      1
      2
      3
      4
      5
      axios.get('/user/12345', {
      validateStatus: function (status) {
      return status < 500; // 状态码在大于或等于500时才会 reject
      }
      })
    • kidish的封装:

      1
      2
      3
      .catch(e  => {
      e.response ? cb(e.response) : cb({status: 500,data:{result: 'errInter'}})
      })

    3、jQuery中的Ajax

    jQuery.ajax( url [, settings ] )
    中文文档 settings参数及设置

    1
    2
    3
    4
    5
    6
    7
    $.ajax({url:  "api/articles?type=more&category=home&shown_offset=1540351013034122&first_view=false",
    contentType: "application/json"
    }).done(function(res){
    console.log(res);
    }).fail(function(){
    console.log("Error: " + err.status);
    })

    更多使用,总感觉用到了才知道。。。。。。

    4、番外

    Fetch
    Fetch 是浏览器提供的原生 AJAX 接口。
    XMLHttpRequest不符合关注分离原则,且基于事件的异步模型写起来也没有现代的 Promise,generator/yield,async/await 友好,因此Fetch出现正是来解决这一问题。

    • Fetch 优点主要有:

      1. 语法简洁,更加语义化
      2. 基于标准 Promise 实现,支持 async/await
      3. 同构方便,使用 isomorphic-fetch
    • 缺点:浏览器支持率不高

    • 使用:
      安装:npm install whatwg-fetch --save
      为了兼容老版本的浏览器,还需要安装 npm install es6-promise --save
      引入:

      1
      2
      import 'whatwg-fetch'
      import 'es6-promise'

      ! Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials: 'include'})
      基本写法参考:参考学习文章

    • 其余学习参考
      参考学习文章:传统 Ajax 已死,Fetch 永生
      参考学习文章:什么是Fetch

    目前还未应用,暂时做一个了解,后续待深入学习~

  • 相关阅读:
    fastjson 使用方法
    算法
    SHA算法
    MD5算法
    kindle推送服务
    DLL劫持
    Hook编程
    Hook技术
    权限验证
    虚拟机
  • 原文地址:https://www.cnblogs.com/lijianming180/p/12360908.html
Copyright © 2011-2022 走看看