理解 ajax、fetch和axios

背景
  • ajax
  • fetch、axios
优缺点
  • ajax基于jquery,引入时需要引入庞大的jquery库,不符合当下前端框架,于是fetch替代了ajax

  • 由于fetch是比较底层,需要我们再次封装,比如data参数配置

    // jquery ajax
    $.post(url, {name: 'test'})
    // fetch
    fetch(url, {
        method: 'POST',
        body: Object.keys({name: 'test'}).map((key) => {
            return encodeURIComponent(key) + '=' + ncodeURIComponent(params[key]);
        }).join('&')
    })
    
  • fetch不支持超时控制,即timeout

详解axios

axios是什么

基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中

axios的特点

1. 从浏览器中创建 XMLHttpRequests
2. 从 node.js 创建 http 请求
3. 支持 Promise API支持 Promise API
4. 拦截请求和响应 (就是有interceptor,拦截器)
5. 转换请求数据和响应数据
6. 取消请求
7. 自动转换 JSON 数据
8. 客户端支持防御 XSRF

拦截器原理

拦截器

兼容性

火狐 谷歌 ie Edge safari

安装

npm install axios

用法

//执行get请求
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
 console.log(response);
}).catch(function (error) {
 console.log(error);
});

// Optionally the request above could also be done as
axios.get('/user', {
 params: {
   ID: 12345
 }
}).then(function (response) {
 console.log(response);
}).catch(function (error) {
 console.log(error);
});

使用流程

//首先创建一个Axios实例
var axiosIns = axios.create({
    baseURL: '请求地址',
    timeout: 延时时长,
    headers: {'X-product': 'h5'}
})
//设置request拦截器
axiosIns.interceptors.request.use(request=>{
    //处理request,可以对所有请求统一处理请求头等
})
//response拦截器
axiosIns.interceptors.response.use(response=>{
    //处理response,可以对所有响应做处理
})

//实例方法
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]])

//请求配置
{
  baseURL: 'https://www.tomandjerry.club/api/',
    url: '/user',
    method: 'get',
    //transformRequest 允许在向服务器发送前,修改请求数据,
    //只能用在PUT POST PATCH 这几个请求方法中,
    //后面的数组中的函数必须返回一个字符串,或ArrayBuffer,或Stream
    transformRequst: [function(data){
        //对data进行任意转换处理
        return data;
    }],
    //transformResponse 在传递给then/catch 前,允许修改响应数据
    transformResponse: [function(data){
        //对data进行任意转换处理
    }],
    //自定义请求头
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    //params 必须是一个 无格式对象 或 URLSearchParams对象
    params: {
        ID: 1234
    },
    //paramsSerializer 是负责params序列化的函数
    //什么是序列化和反序列化,见下
    paramsSerializer: function(params){
        return Qs.strinfify(params,{arrayFormat: 'brackets'})
    },
    //data 主体的发送数据
    //只适用于PUT POST 和PATCH
    //在没有设置transformRequest时,必须是以下类型之一
    //string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    //浏览器专属:FomData,File,Blob
    //Node专属:Stream
    data: {
        firstName: 'Jack'
    },
    //timeout 请求超时,如果请求超过了timeout指定的时间则请求将被中断
    timeout: 1000,
    //表示跨域请求时是否需要使用凭证
    withCredentials: false,//默认的
    //adapter 允许自定义处理请求,使测试更轻松
    //返回 一个promise并应用一个有效的响应
    adapter: function(config){
        
    },
    //auth 表示应该使用HTTP基础验证,并提供凭据
    //将设置一个Authorization头,覆写掉现有的任意使用headers设置的自定义Authorization头
    auth: {
        username: 'janedoe',
        password: 'ssss'
    },
    //responseType 表示服务器响应的数据类型,
    //可以是arraybuffer blob document json text stream
    responseType: 'json',//默认
    //xsrfCookieName 是用作xsrf token 的值的cookie的名称
    xsrfCookieName: 'XSRF-TOKEN',//默认
    //xsrfHeaderName 是承载xsrf token 的值的HTTP头的名称
    xsrfHeaderName: 'X-XSRF-TOKEN', // 默认
    //onUploadProgress 允许为上传处理进度事件
    onUploadProgress: function(progressEvent){
        // 对原生进度事件的处理
    },
    //onDownloadProgress 允许为下载处理进度事件
    onDownloadProgress: function(progressEvent){
        //对原生进度事件的处理
    },
    //maxContentLength 定义允许的响应内容的最大尺寸
    maxContentLength: 2000,
    //validateStatus 定义对于给定的HTTP 响应状态码是 resolve 或 reject  
    //如果validateStatus返回true(或者设置为 `null` 或 `undefined`),
    //promise 将被 resolve; 否则,promise 将被 rejecte
    validateStatus: function (status) {
        return status >= 200 && status < 300; // 默认
     },
     //maxRedirects 定义在 node.js 中 follow 的最大重定向数目
     // 如果设置为0,将不会 follow 任何重定向
     maxRedirects: 5, // 默认的
     //httpAgent和httpsAgent分别在node.js中用于定义在执行http和https 时使用的自定义代理。
     //允许像这样配置选项:keepAlive默认没有启用
     httpAgent: new http.Agent({ keepAlive: true }),
     httpsAgent: new https.Agent({ keepAlive: true }),
     //proxy定义代理服务器的主机名称和端口,auth表示HTTP基础验证应当用于连接代理,并提供凭据
     //这将会设置一个Proxy-Authorization头,
     //覆写掉已有的通过使用header设置的自定义Proxy-Authorization头。
     proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: : {
          username: 'mikeymike',
          password: 'rapunz3l'
        }
      },
      //cancelToken 指定用于取消请求的 cancel token
     cancelToken: new CancelToken(function (cancel) {
     
      })
}
序列化

解释

在程序运行的过程中,所有变量都是存在内存中
d = dict(name='Bob', age=20, score=88)
可以随时修改变量,比如把name改成'Bill',但是一旦程序结束,所有变量所占用的内存就会被操作系统回收,下次重新运行变量又被重新初始化为'Bob',我们把变量从内存中变成可储存或传输的过程称之为序列化。在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等。序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。反之把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
参考

https://www.jianshu.com/p/065294e2711c

https://github.com/axios/axios

https://juejin.im/post/5acde23c5188255cb32e7e76

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143192607210600a668b5112e4a979dd20e4661cc9c97000

猜你喜欢

转载自www.cnblogs.com/TomAndJerry/p/10611400.html