zoukankan      html  css  js  c++  java
  • 请求

    实际应用示例

    • 前端不需要做统一的接口防重
      • 前端无法通过判断接口是否返回来释放按钮(因为可以手动刷新页面,将导致刷新前请求丢失)
      • 后端对接口做了防重

    通过增加时间戳避免IE9的get请求缓存问题

    axios.interceptors.request.use(function (response) {
        if (method === 'get' && isIE) {
            config.url += `${!config.url.includes('?') ? '?' : '&'}timeStamp=${new Date().getTime()}`;
        }
    })
    

    添加响应拦截器,统一处理异常请求状态

      axios.interceptors.response.use(
        res => {
          // 对响应数据进行处理
          return res
        },
        err => {
          const errInfo = err.response;
          if (errInfo) {
            switch (errInfo.status) {
              case 403: 
                // 403 服务器拒绝请求。
                break;
              case 404:
                // 404 服务器找不到请求的网页。
                break;
              case 401:
                // 401 请求要求身份验证。
                break;
              case 400:
                // 服务器不理解请求的语法。
                break;
              case 500:
                // 服务器遇到错误,无法完成请求。
                break;
            }
          }
          return Promise.reject(err);
        }
      );
    

    —————————————————————————————————————————————————————————

    使用配置创建自定义实例

    配置会以一个优先顺序进行合并

    • 在 lib/defaults.js 找到的库的默认值
    • 通过 axios.defaults 修改的全局默认值
    • 然后是实例的 defaults 属性(defaults 属性:实例的默认属性。有两种方法设置,一种 create 创建实例时传入,一种创建实例后通过 defaults 属性修改)
    • 最后是请求的 config 参数
    // 通过 defaults 设置全局的 axios 默认值
    axios.defaults.baseURL = 'https://api.example.com';
    axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;    // 影响所有?
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';    // 只影响post请求?
    // 可以自定义defaults下的属性,在请求的其他地方通过请求对象获取该值
    axios.defaults.loginUrl = "http://ihrsit.midea.com:8088/login/ihr/login"; 
    
    // 创建实例时设置配置的默认值
    const instance = axios.create({
      baseURL: 'https://api.example.com'
    });
    
    // 在实例已创建后修改默认值
    instance.defaults.timeout = 2500; // 现在,在超时前,所有请求都会等待 2.5 秒
    instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; // 设置全部的请求的请求头?,注意这里的common应该是值全部的请求类型
    
    
    // 请求时的 config 参数
    instance.get('/longRequest', {
      timeout: 5000
    });
    

    可配置项

    {
      // `url` 是用于请求的服务器 URL
      url: '/user',
    
      // `method` 是创建请求时使用的方法
      method: 'get', // 默认是 get
    
      // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
      // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
      baseURL: 'https://some-domain.com/api/',
    
      // `headers` 是即将被发送的自定义请求头
      headers: {'X-Requested-With': 'XMLHttpRequest'},
    
      // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)默认为0
      // 如果请求话费了超过 `timeout` 的时间,请求将被中断
      // 这个超时时间在谷歌中似乎无效?,待验证
      timeout: 1000,
    
      // `withCredentials` 表示跨域请求时是否需要使用凭证(凭证,例如cookie)
      // 指访问的这个跨域接口,能不能设置自己域下的cookie,如果为为false,那么不允许设置该接口域名下的cookie。
      // 通过设置为true而获得的接口,同样遵守同源策略。当前窗口下的其他域名是不能够访问这个cookie的
      // 存在兼容性问题
      withCredentials: false, // 默认的
    
      // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
      responseType: 'json', // 默认的
    
      // XSRF(跨站请求伪造)网站 B 使用 get 请求网站 A 的接口时,会自动带上 A 的 COOKIE,如果 A 的 token 保存在 COOKIE 中就会被冒用身份。
      // 例如:在一个论坛中,某人上传了携带 XSRF 攻击的图片(该图片的 src 实际为 A 网站的接口),当其他用户加载这个图片时,携带 COOKIE 的请求就会被发起,身份可能被冒用。
      // 防范方法
            // 通过请求头Referer(请求来源域名)判断请求是否来自于合法服务器
            // 在HTTP请求头部添加自定义key,一般为 csrftoken 并把 token 值放入其中
      // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称(该值放在cookie中?放在cookie有什么意义,不是也会被跨域攻击?)
      // xsrf token 似乎和顶部的csrftoken是同一个概念
      xsrfCookieName: 'XSRF-TOKEN', // default
    
      // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
      xsrfHeaderName: 'X-XSRF-TOKEN', // 默认的
    
      // `maxContentLength` 定义允许的响应内容的最大尺寸
      maxContentLength: 2000,    // 以什么为单位?
    
    ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————改变请求响应参数
    
      // `params` 是即将与请求一起发送的 URL 参数(会被拼接到URL的?后面)?
      // 必须是一个无格式对象或 URLSearchParams 对象
      // 无格式对象,plain object通过字面量形式或者new Object()形式定义的对象。特点是它的原型直接指向根原型,不存在多级原型链
      // URLSearchParams URL查询字符串对象(满足URL查询格式的字符串?)
      params: {
        ID: 12345
      },
    
      // `paramsSerializer` 是一个负责 `params` 序列化的函数
      paramsSerializer: function(params) {
        // Qs.stringify:Qs库的一个方法,把一个参数对象格式化为一个字符串
        return Qs.stringify(params, {arrayFormat: 'brackets'})    
      },
    
      // `data` 是作为请求主体被发送的数据
      // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
      // 在没有设置 `transformRequest` 时,必须是以下类型之一:
      // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
      // ArrayBufferView 没有特定的实体,是指一类二进制数据对象,叫类数组数据
      // - 浏览器专属:FormData, File, Blob
      // Blob 二进制大对象
      // - Node 专属: Stream
      data: {
        firstName: 'Fred'
      },
    
      // `transformRequest` 允许在向服务器发送前,修改请求数据
      // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
      // 通过 axios.defaults.transformRequest = [function] 设置会导致get请求的数据也被修改
      // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer(二进制数据缓冲区),或 Stream(流)
      // 默认转为 JSON 数据?
      transformRequest: [function (data) { // 这里用了一个数组,是依次修改的意思吗?
        // 对 data 进行任意转换处理
    
        return data;
      }],
    
      // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
      transformResponse: [function (data) {
        // 对 data 进行任意转换处理
    
        return data;
      }],
    
      // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
      // 该函数可以通过 http 相应状态码来设置接口对应的 promise 的状态,当 validateStatus 函数返回 true 时,promise 将被 resolve(成功); 否则,promise 将被 reject(失败)
      validateStatus: function (status) {
        return status >= 200 && status < 300; // 默认的,当状态码200-300间时,axios返回resolve状态的promise否则返回rejecte状态的
      },
    
    ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————其他方法
    
      // `onUploadProgress` 允许为上传处理进度事件
      onUploadProgress: function (progressEvent) {    // xhr.upload.onprogress事件的处理函数
        // XMLHttpRequest.upload 只读对象,用来表示上传的进度,作为一个XMLHttpRequestEventTarget,可以通过对其绑定事件来追踪它的进度。
        // 可以被绑定在upload对象上的事件监听器如下:
        // onloadstart	获取开始、onprogress	数据传输进行中、onabort	获取操作终止、onerror	获取失败、onload	获取成功、ontimeout	获取操作在用户规定的时间内未完成、onloadend	获取完成(不论成功与否)
        // XMLHttpRequestEventTarget.onprogress 是在 XMLHttpRequest 完成之前周期性调用的函数。
        // XMLHttpRequest.onprogress = function (event) {
        //   event.loaded; // 周期性调用中接受到了多少信息?
        //   event.total; // 该请求一共有多少信息。?
        // };
        // 对原生进度事件的处理
      },
    
      // `onDownloadProgress` 允许为下载处理进度事件
      onDownloadProgress: function (progressEvent) {
        // XMLHttpRequest 没有对应的属性指向下载对象,这个方法是如何实现的?
        // 对原生进度事件的处理
      },
    
      // `cancelToken` 指定用于取消请求的 cancel token(取消令牌)
      // cancelToken 期望传入由构造函数 axios.CancelToken 返回的对象
      // 该构造函数接收一个函数作为参数,并把取消方法 cancel 传入这个函数中,当cancel被调用时请求就会被取消。
      //(生成的对象应该有某个属性指向我们传入的函数,后文的例子是用独立变量保存这个取消函数并不理想)
      cancelToken: new CancelToken(function (cancel) {    // CancelToken构造函数需要事先声明,见下文中的取消专题
      })
    
      // `adapter` 允许自定义处理请求,以使测试更轻松
      // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
      adapter: function (config) {
        /* ... */
      },
    
    ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————服务器
    
      // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
      // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头。一般用在非浏览器上(用在代理服务器上?)
      // Authorization 请求消息头含有服务器用于验证用户代理身份的凭证,通常会在服务器返回401 Unauthorized 状态码以及WWW-Authenticate 消息头之后在后续请求中发送此消息头。
      // 401 Unauthorized 状态码 : 代表该接口未经许可
      auth: {
        username: 'janedoe',
        password: 's00pers3cret'
      },
    
      // `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'
        }
      },
    }
    

    创建实例的方法

    • 当需要对各类型请求方式设置不同配置项时创建,仅仅只是统一修改全局配置用 axios.defaults 更方便
    • axios.create([config]) 使用自定义配置新建一个 axios 实例,实例继承axios的所有方法
    var instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000, // 以毫秒为单位
      headers: {'X-Custom-Header': 'foobar'}
    });
    
    • 以下是可用的实例方法。指定的配置将与实例的配置合并。
      • axios#request(config)
      • axios#get(url[, config])
      • axios#delete(url[, config])
      • axios#head(url[, config])
      • axios#options(url[, config])
      • axios#post(url[, data[, config]])
      • axios#put(url[, data[, config]])
      • axios#patch(url[, data[, config]])

    使用 application/x-www-form-urlencoded 格式化数据

    • 默认情况下,axios将JavaScript对象序列化为JSON。
      • get 默认是 application/x-www-form-urlencoded,不会显示 Content-Type,表现为不可折叠按键值显示
      • post 默认为 JSON,表现为可折叠对象
      • 当 axios.post 第二个参数是字符串时,默认为 application/x-www-form-urlencoded,这个字符串作为 name1=value1链的name
    • 要以application / x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。
      • 在请求头的Content-type表明请求的数据格式(设置了请求头似乎并不会自动转换格式)
      • application / x-www-form-urlencoded 编码方式把数据转换成一个字串(name1=value1&name2=value2…)(会自动检测数据类型)

    浏览器

    • 在浏览器中,您可以使用URLSearchParams API
      • URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串。
      • 兼容性在IE并不理想
    const params = new URLSearchParams();
    params.append('param1', 'value1');
    params.append('param2', 'value2');
    axios.post('/foo', params);
    
    • 可以使用qs库编码数据:
    import qs from 'qs';
    const data = { 'bar': 123 };
    const options = {
      method: 'POST',
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      data: qs.stringify(data),
      url,
    };
    axios(options);
    

    Node.js

    • 在node.js中,您可以使用querystring模块
      • querystring 模块提供用于解析和格式化 URL 查询字符串的实用工具。
    const querystring = require('querystring');
    axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
    

    —————————————————————————————————————————————————————————

    拦截器(分为请求和拦截)

    添加拦截器

    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        // config 应该是请求的配置和传参
        return config;
    
        // 还可以返回 promise.reject 来拒绝请求
        return Promise.reject(error);
      }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
      });
    
    // 添加响应拦截器,可以为自定义 axios 实例添加拦截器
    axios.interceptors.response.use(function (response) {
        // 对响应数据做点什么
        return response;
      }, function (error) {
        // error.config 包含了 axios 请求的参数,包括 url 和 method
        // 对响应错误做点什么
        return Promise.reject(error);
      });
    

    移除拦截器

    const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
    axios.interceptors.request.eject(myInterceptor);
    
    • 可以为自定义 axios 实例添加拦截器

    —————————————————————————————————————————————————————————

    发起请求

    axios.request(config):实际上所有aixos请求的创建都是request方法来实现的。

    axios.request({
         url: "http://example.com",
         method: "get",
         headers:{
             Cookie: "cookie1=value; cookie2=value; cookie3=value;"
         } 
    }).then(...)
    

    axios(config):传递相关配置来创建请求

    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
    
    // 获取远端图片
    axios({
      method:'get',
      url:'http://bit.ly/2mTM3nY',
      responseType:'stream' // responseType表示期望服务器响应的数据类型
    })
      .then(function(response) {
        // pipie nodejs中对流数据的一种操作
        // fs nodejs中文件对象
        // fs.createWriteStream 保存文件
      response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
    });
    

    axios(url[, config]):发送 GET 请求

    // 发送 GET 请求(默认的方法)
    axios('/user/12345');
    

    axios.get(url[, config])

    axios.get('/user?ID=12345')
    // 可写为
    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
    

    axios.delete(url[, config])

    axios.head(url[, config])

    • HEAD跟get很像,但是不返回响应体信息,用于检查对象是否存在,并获取包含在响应消息头中的信息。

    axios.post(url[, data[, config]])

    • post 向指定资源提交数据进行处理的请求,用于添加新的内容。
    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
    

    axios.put(url[, data[, config]])

    • put 向指定资源位置上传其最新的内容,用于修改某个内容。(存在则替换,不存在则创建。)

    axios.patch(url[, data[, config]])

    • patch 用来更新局部资源,相对于put而言
    • PATCH是幂等的,幂等是指这个请求任意多次执行所产生的影响均与一次执行的影响相同

    —————————————————————————————————————————————————————————

    并发

    • axios.all(iterable):当所有的请求都完成后,会收到一个数组,包含着响应对象,其中的顺序和请求发送的顺序相同,可以使用 axios.spread 分割成多个单独的响应对象(?)
    • axios.spread(callback)
    function getUserAccount() {
      return axios.get('/user/12345');
    }
    
    function getUserPermissions() {
      return axios.get('/user/12345/permissions');
    }
    
    axios.all([getUserAccount(), getUserPermissions()])
      .then(axios.spread(function (acct, perms) {    //两个参数分别对应两个请求的返回
        // 两个请求现在都执行完成
      }));
    

    —————————————————————————————————————————————————————————

    取消

    • Axios 的 cancel token API(取消令牌) 基于cancelable promises proposal(无法兑现的promise建议),它还处于第一阶段。
    • 取消后,在谷歌的控制台中,请求状态变为canceled
    • 可以使用 CancelToken.source 工厂方法创建 cancel token
    var CancelToken = axios.CancelToken;    
    var source = CancelToken.source();   // axios自带的取消令牌,应该是常用方法的一种便捷入口而已,本质和new axios.CancelToken 返回实例是一致的
    
    axios.get('/user/12345', {
      cancelToken: source.token // 设置令牌对象
    }).catch(function(thrown) {    // 取消请求会进入catch
      if (axios.isCancel(thrown)) {    // isCancel判断是否由axios发起的取消
        console.log('Request canceled', thrown.message);    // thrown.message来源于cancel函数的传参,见最后
      } else {
        // 处理错误
      }
    });
    
    // 带参数
    axios.post('/user/12345', {
      name: 'new name'
    }, {
      cancelToken: source.token
    })
    
    // 取消请求(message 参数是可选的)
    source.cancel('Operation canceled by the user.');
    
    • 可以通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token
    var CancelToken = axios.CancelToken;
    var cancel;
    
    axios.get('/user/12345', {
      cancelToken: new CancelToken(function executor(c) {
        // executor 函数接收一个 cancel 函数作为参数
        cancel = c;
      })
    });
    
    // 取消请求
    cancel();
    
    • 可以使用同一个 cancel token 取消多个请求(应该是配置了同一个令牌的接口,能被同一个令牌取消)

    —————————————————————————————————————————————————————————

    错误处理

    // 错误有以下几种
    // 请求发起失败
    // 请求发起成功,没有任何响应(响应错误)
    // 成功响应,响应返回 200 以外的值?
    axios.get('/user/12345')
      .catch(function (error) {
        if (error.response) {
          // 请求已经发起,服务器已经返回了响应状态码
          // 状态码不是 2xx 时(需要使用 validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围。)
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
          // 响应错误时(请求已发出,未收到响应,例如超时)
          // `error.request` 在浏览器中是 XMLHttpRequest 实例
          // 在 node.js 中是 http.ClientRequest 实例 
          console.log(error.request);
        } else {
          // 请求发起错误(请求未正确发起)
          console.log('Error', error.message);
        }
        console.log(error.config);
      });
    

    —————————————————————————————————————————————————————————

    响应结构

    • then
    {
      // `data` 由服务器提供的响应
      data: {},    // 不一定为对象
    
      // `status` 来自服务器响应的 HTTP 状态码
      status: 200,
    
      // `statusText` 来自服务器响应的 HTTP 状态信息
      statusText: 'OK',
    
      // `headers` 服务器响应的头
      headers: {},
    
      // `config` 是为请求提供的配置信息
      config: {}
    
      // `request` 代表生成此相应请求的对象
      // 在node.js 中如果有重定向,它指向最后一个重定向产生的请求
      // 在浏览器中它是一个 XMLHttpRequest实例
      request: {}
    }
    
    • 在使用 catch 时,或传递 rejection callback 作为 then 的第二个参数时,响应可以通过 error 对象获取(catch函数中 error.response 返回完整的响应,包括staue等)
      • promise 中使用 catch 只是 then 的语法糖,实际就是 then(undefined, catchFun) 的简易写法
    axios.get('/user/12345')
      .then(function(response) {
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.headers);
        console.log(response.config);
        // 没有response.request
      });
    

    —————————————————————————————————————————————————————————

    安装

    npm install axios
    

    其他

    • 请求类型执行一种直观的接口类型说明,其实现逻辑还是依赖于后端代码。当然,可以用公共的代码对相同类型的接口做统一处理

    —————————————————————————————————————————————————————————

    另一篇随笔整合在一起

    原文地址 www.npmjs.com

    axios API

    Requests can be made by passing the relevant config to axios. 通过传入 config 来发起请求

    axios(config)
    // Send a POST request
    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
    
    // GET request for remote image in node.js
    axios({
      method: 'get',
      url: 'http://bit.ly/2mTM3nY',
      responseType: 'stream'
    })
      .then(function (response) {
        response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
      });
    
    axios(url[, config])
    // Send a GET request (default method)
    axios('/user/12345');
    

    Request method aliases 请求方法别名

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

    Concurrency (Deprecated) 已经废弃

    Please use Promise.all to replace the below functions. 使用 Promise.all 代替 axios.all

    Creating an instance 创建实例

    axios.create([config])
    const instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    });
    

    Instance methods 实例的方法

    The available instance methods are listed below. The specified config will be merged with the instance config. 实例方法中的 config 优先于创建实例时传入的 config

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

    Request Config 请求 config

    {
      url: '/user',
      method: 'get', // default
    
      // `baseURL` will be prepended to `url` unless `url` is absolute. 当 url 是绝对地址是 baseURL 不被添加为前缀
      baseURL: 'https://some-domain.com/api/',
    
      // `transformRequest` allows changes to the request data before it is sent to the server 在请求发起前对 data 进行修改,请求在拦截器之后发起
      // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, 最后一个函数必须返回 string, Buffer, ArrayBuffer, FormData, Stream(流)
      // FormData or Stream
      // You may modify the headers object. 可以修改 headers 对象
      // 注释:transformRequest 的默认值应该是 [function(data, headers) JSON.stringify(data)]
      transformRequest: [function (data, headers) {
        return data;
      }],
    
      // `transformResponse` allows changes to the response data to be made before 在响应拦截之前修改响应数据
      // 注释:默认应该是 JSON.parse,响应数据的类型由服务器决定,服务器会参考请求头中 Accept 来决定返回的数据序列化方式。
      transformResponse: [function (data) {
        return data;
      }],
    
      // 注释:headers['Content-Type'] 会影响浏览器控制台对参数的展示方式
      // 注释:axios 会根据 data 参数的数据类型设置 headers['Content-Type']
      headers: {'X-Requested-With': 'XMLHttpRequest'},
    
      // Must be a plain object or a URLSearchParams object 必须是普通对象或 URLSearchParams
      params: {
        ID: 12345
      },
    
      // `paramsSerializer` is an optional function in charge of serializing `params` 用于序列化 params
      // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
      paramsSerializer: function (params) {
        return Qs.stringify(params, {arrayFormat: 'brackets'})
      },
    
      // When no `transformRequest` is set, must be of one of the following types: 如果未设置 transformRequest 必须是以下类型之一
      // - string, plain object(简单对象), ArrayBuffer, ArrayBufferView, URLSearchParams
      // - Browser only: FormData, File, Blob
      // - Node only: Stream, Buffer
      data: {
        firstName: 'Fred'
      },
      
      // syntax alternative to send data into the body ?
      // method post
      // only the value is sent, not the key
      data: 'Country=Brasil&City=Belo Horizonte',
    
      timeout: 1000, // default is `0` (no timeout)
    
      // `withCredentials` indicates whether or not cross-site Access-Control requests 跨域请求是是否发送以 Access-Control 开头的头部
      // should be made using credentials
      withCredentials: false, // default
    
      // Return a promise and supply a valid response (see lib/adapters/README.md).返回 promise,可以自定义响应
      adapter: function (config) {
        /* ... */
      },
    
      // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. http 身份认证传参
      // This will set an `Authorization` header, overwriting any existing 将覆盖 headers.Authorization
      // `Authorization` custom headers you have set using `headers`.
      // Please note that only HTTP Basic auth is configurable through this parameter.只在 http 身份认证时覆盖
      // For Bearer tokens and such, use `Authorization` custom headers instead. 其他场景依然使用 headers.Authorization
      auth: {
        username: 'janedoe',
        password: 's00pers3cret'
      },
    
      // `responseType` indicates the type of data that the server will respond with 服务器响应数据的类型,只能是下列之一
      // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
      //   browser only: 'blob'
      responseType: 'json', // default
    
      // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) 解码响应的编码方式,仅作用于 Node.js 环境
      responseEncoding: 'utf8', // default
    
      // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token 当需要 xsrf 令牌时,headers 传递的令牌 key 的名称
      xsrfCookieName: 'XSRF-TOKEN', // default
    
      // `xsrfHeaderName` is the name of the http header that carries the xsrf token value 当需要 xsrf 令牌时,headers 传递的令牌 value 的名称
      xsrfHeaderName: 'X-XSRF-TOKEN', // default
    
      // `onUploadProgress` allows handling of progress events for uploads 用来处理上载进度的函数
      // browser only
      onUploadProgress: function (progressEvent) {
        // Do whatever you want with the native progress event
      },
    
      // `onDownloadProgress` allows handling of progress events for downloads 用来处理下载进度的函数
      // browser only
      onDownloadProgress: function (progressEvent) {
        // Do whatever you want with the native progress event
      },
    
      // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js 在 node.js 环境下定义响应的最大大小
      maxContentLength: 2000,
    
      // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed 在 node.js 环境下定义请求的 body 的最大大小
      maxBodyLength: 2000,
    
      validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    
      // `maxRedirects` defines the maximum number of redirects to follow in node.js. 在 node.js 中最大重定向次数
      // If set to 0, no redirects will be followed. 设置为 0 时不进行重定向
      maxRedirects: 5, // default
    
      // `socketPath` defines a UNIX Socket to be used in node.js.
      // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
      // Only either `socketPath` or `proxy` can be specified.
      // If both are specified, `socketPath` is used.
      socketPath: null, // default
    
      // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
      // and https requests, respectively, in node.js. This allows options to be added like
      // `keepAlive` that are not enabled by default.
      httpAgent: new http.Agent({ keepAlive: true }),
      httpsAgent: new https.Agent({ keepAlive: true }),
    
      // `proxy` defines the hostname, port, and protocol of the proxy server.
      // You can also define your proxy using the conventional `http_proxy` and
      // `https_proxy` environment variables. If you are using environment variables
      // for your proxy configuration, you can also define a `no_proxy` environment
      // variable as a comma-separated list of domains that should not be proxied.
      // Use `false` to disable proxies, ignoring environment variables.
      // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
      // supplies credentials.
      // This will set an `Proxy-Authorization` header, overwriting any existing
      // `Proxy-Authorization` custom headers you have set using `headers`.
      // If the proxy server uses HTTPS, then you must set the protocol to `https`. 
      proxy: {
        protocol: 'https',
        host: '127.0.0.1',
        port: 9000,
        auth: {
          username: 'mikeymike',
          password: 'rapunz3l'
        }
      },
    
      // `cancelToken` specifies a cancel token that can be used to cancel the request
      // (see Cancellation section below for details)
      cancelToken: new CancelToken(function (cancel) {
      }),
    
      // `decompress` indicates whether or not the response body should be decompressed 
      // automatically. If set to `true` will also remove the 'content-encoding' header 
      // from the responses objects of all decompressed responses
      // - Node only (XHR cannot turn off decompression)
      decompress: true // default
    
    }
    
    

    Response Schema

    The response for a request contains the following information.

    {
      // `data` is the response that was provided by the server
      data: {},
    
      // `status` is the HTTP status code from the server response
      status: 200,
    
      // `statusText` is the HTTP status message from the server response
      statusText: 'OK',
    
      // `headers` the HTTP headers that the server responded with
      // All header names are lower cased and can be accessed using the bracket notation.
      // Example: `response.headers['content-type']`
      headers: {},
    
      // `config` is the config that was provided to `axios` for the request
      config: {},
    
      // `request` is the request that generated this response
      // It is the last ClientRequest instance in node.js (in redirects)
      // and an XMLHttpRequest instance in the browser
      request: {}
    }
    
    

    When using then, you will receive the response as follows:

    axios.get('/user/12345')
      .then(function (response) {
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.headers);
        console.log(response.config);
      });
    
    

    When using catch, or passing a rejection callback as second parameter of then, the response will be available through the error object as explained in the Handling Errors section.

    Config Defaults

    You can specify config defaults that will be applied to every request.

    Global axios defaults

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

    Custom instance defaults

    // Set config defaults when creating the instance
    const instance = axios.create({
      baseURL: 'https://api.example.com'
    });
    
    // Alter defaults after instance has been created
    instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    
    

    Config order of precedence

    Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.

    // Create an instance using the config defaults provided by the library
    // At this point the timeout config value is `0` as is the default for the library
    const instance = axios.create();
    
    // Override timeout default for the library
    // Now all requests using this instance will wait 2.5 seconds before timing out
    instance.defaults.timeout = 2500;
    
    // Override timeout for this request as it's known to take a long time
    instance.get('/longRequest', {
      timeout: 5000
    });
    
    

    Interceptors

    You can intercept requests or responses before they are handled by then or catch.

    // Add a request interceptor
    axios.interceptors.request.use(function (config) {
        // Do something before request is sent
        return config;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });
    
    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response;
      }, function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
      });
    
    

    If you need to remove an interceptor later you can.

    const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
    axios.interceptors.request.eject(myInterceptor);
    
    

    You can add interceptors to a custom instance of axios.

    const instance = axios.create();
    instance.interceptors.request.use(function () {/*...*/});
    
    

    Handling Errors

    axios.get('/user/12345')
      .catch(function (error) {
        if (error.response) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
          // The request was made but no response was received
          // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
          // http.ClientRequest in node.js
          console.log(error.request);
        } else {
          // Something happened in setting up the request that triggered an Error
          console.log('Error', error.message);
        }
        console.log(error.config);
      });
    
    

    Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

    axios.get('/user/12345', {
      validateStatus: function (status) {
        return status < 500; // Resolve only if the status code is less than 500
      }
    })
    
    

    Using toJSON you get an object with more information about the HTTP error.

    axios.get('/user/12345')
      .catch(function (error) {
        console.log(error.toJSON());
      });
    
    

    Cancellation

    You can cancel a request using a cancel token.

    The axios cancel token API is based on the withdrawn cancelable promises proposal.

    You can create a cancel token using the CancelToken.source factory as shown below:

    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    
    axios.get('/user/12345', {
      cancelToken: source.token
    }).catch(function (thrown) {
      if (axios.isCancel(thrown)) {
        console.log('Request canceled', thrown.message);
      } else {
        // handle error
      }
    });
    
    axios.post('/user/12345', {
      name: 'new name'
    }, {
      cancelToken: source.token
    })
    
    // cancel the request (the message parameter is optional)
    source.cancel('Operation canceled by the user.');
    
    

    You can also create a cancel token by passing an executor function to the CancelToken constructor:

    const CancelToken = axios.CancelToken;
    let cancel;
    
    axios.get('/user/12345', {
      cancelToken: new CancelToken(function executor(c) {
        // An executor function receives a cancel function as a parameter
        cancel = c;
      })
    });
    
    // cancel the request
    cancel();
    
    

    Note: you can cancel several requests with the same cancel token.

    Using application/x-www-form-urlencoded format

    By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

    Browser

    In a browser, you can use the URLSearchParams API as follows:

    const params = new URLSearchParams();
    params.append('param1', 'value1');
    params.append('param2', 'value2');
    axios.post('/foo', params);
    
    

    Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

    Alternatively, you can encode data using the qs library:

    const qs = require('qs');
    axios.post('/foo', qs.stringify({ 'bar': 123 }));
    
    

    Or in another way (ES6),

    import qs from 'qs';
    const data = { 'bar': 123 };
    const options = {
      method: 'POST',
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      data: qs.stringify(data),
      url,
    };
    axios(options);
    
    

    Node.js

    Query string

    In node.js, you can use the querystring module as follows:

    const querystring = require('querystring');
    axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
    
    

    or 'URLSearchParams' from 'url module' as follows:

    const url = require('url');
    const params = new url.URLSearchParams({ foo: 'bar' });
    axios.post('http://something.com/', params.toString());
    
    

    You can also use the qs library.

    NOTE

    The qs library is preferable if you need to stringify nested objects, as the querystring method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).

    Form data

    In node.js, you can use the form-data library as follows:

    const FormData = require('form-data');
     
    const form = new FormData();
    form.append('my_field', 'my value');
    form.append('my_buffer', new Buffer(10));
    form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
    
    axios.post('https://example.com', form, { headers: form.getHeaders() })
    
    

    Alternatively, use an interceptor:

    axios.interceptors.request.use(config => {
      if (config.data instanceof FormData) {
        Object.assign(config.headers, config.data.getHeaders());
      }
      return config;
    });
    
    

    Semver

    Until axios reaches a 1.0 release, breaking changes will be released with a new minor version. For example 0.5.1, and 0.5.4 will have the same API, but 0.6.0 will have breaking changes.

    Promises

    axios depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill.

    TypeScript

    axios includes TypeScript definitions.

    import axios from 'axios';
    axios.get('/user?ID=12345');
    
    

    Resources

    Credits

    axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

    License

    MIT

  • 相关阅读:
    PyTorch在NLP任务中使用预训练词向量
    使用Google的Colab+pytorch
    深度学习与Pytorch入门实战(十六)情感分类实战(基于IMDB数据集)
    深度学习与Pytorch入门实战(十五)LSTM
    深度学习与Pytorch入门实战(十四)时间序列预测
    深度学习与Pytorch入门实战(十三)RNN
    PyTorch的nn.Linear()详解
    Pytorch中with torch.no_grad()或@torch.no_grad() 用法
    深度学习与Pytorch入门实战(十二)实现ResNet-18并在Cifar-10数据集上进行验证
    深度学习与Pytorch入门实战(十一)数据增强
  • 原文地址:https://www.cnblogs.com/qq3279338858/p/10882479.html
Copyright © 2011-2022 走看看