当前位置: 首页 > news >正文

Axios用法总结(附有封装好的axios请求)

目录

简介

安装

使用方法

axios常用配置项

创建axios实例

设置默认配置

请求拦截器

响应拦截器

批量发送请求

取消请求

axios的二次封装


简介

axios本身不是一种新技术,本质上是基于promise对原生XMLHttpRequest的封装,

官网文档  👉  Getting Started | Axios Docs

axios与ajax的关系?

        ajax实现了无刷新更新数据,是对原生xhr的封装;

        axios是一个基于Promise的http库,是对ajax的封装;

axiso具有如下特点:

  • 基于promise的异步ajax请求库
  • 支持浏览器端和node.js端使用
  • 支持promise API
  • 支持请求、响应拦截器
  • 支持取消请求
  • 支持批量发送多个请求

安装

npm install axios // npm安装
<script src="http://unpkg.com/axios/dist/axios.min.js"> // cdn引入

在vue中使用:

import axios from 'axios'

则该文件中就会有个axios对象;

使用方法

axios常用配置项

axios方法需要传入一个config配置对象,常用的包括:

axios({
  url: '/user/12345', // 请求url地址
  method: 'post',  // 请求方式,post/get/delete等,默认是get方法
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }, // 携带请求体参数, 默认是json格式
  data: 'Country=Brasil&City=Belo Horizonte', // 携带请求体参数, urlencoded编码
  responseType: 'json', // 配置响应数据格式, 默认是json
  baseURL: 'https://some-domain.com/api', // 设置baseURL地址
  headers: {'X-Requested-With': 'XMLHttpRequest'}, // 设置请求头
  timeout: 1000, // 超时时间,未设置默认为0
  params: {
    ID: 12345
  },  // 设置query参数
  withCredentials: false, // 配置跨域时是否需要使用凭证,默认false
  auth: {
    username: '',
    password: ''
    } // 设置一个‘Authorization’头,覆盖掉现有的任意使用'headers'设置的自定义’Athorization‘头
});

官网详细介绍贴一下:

{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  // NOTE: params that are null or undefined are not rendered in the URL.
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - 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` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  // Please note that only HTTP Basic auth is configurable through this parameter.
  // For Bearer tokens and such, use `Authorization` custom headers instead.
  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)
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token 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
  maxContentLength: 2000,

  // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  maxBodyLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  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

}

也可以使用简写形式(仅以put与get为例):

axios.get();
axios.put();
  • axios调用的返回值是Promise实例
  • axios成功后的值是一个由axios封装的response对象,后台数据返回的真正数据在response.data中
  • 携带query参数时,需配置params配置项
  • 携带params参数时,需自己手动将其拼在url中

创建axios实例

   有时候,可能对于不同接口请求的配置不一样,则需要创建不同的axios实例进行使用;创建出来的axios实例除了没有取消请求和批量请求方法之外,其余功能与axios本身一样;

const axiosInstance = axios.create({
    baseURL: 'https://some-domin.com/api/',
    timeout: 1000;
    headers: {'X-Custom-Header': 'footbar'}
})

若多个实例之间有默认的配置,则在创建实例之前设置默认配置即可;

设置默认配置

   可以在axios使用之前为其设置默认配置:

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

设置默认配置后,所有用于请求的axios都将具备该配置;

请求拦截器

在请求发出去之前可以对配置对象进行处理(拦截)(本质是在请求实际发出去之前执行的一个回调函数),记得处理后一定要将配置对象return出去;

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);
});

如果想移除设置的请求拦截器,可以通过:

const myInterceptor = axios.interceptors.request.use(function (config) {/*...*/});
axios.interceptors.request.eject(myInterceptor); // 移除请求拦截器

一般在请求拦截器中追加请求头的token、界面loadding显示等等;

响应拦截器

响应拦截器是在then得到响应之前,对响应进行的处理(本质上也是在给then返回之前执行的一个回调函数);也要记得将结果处理后的结果return出去哦,否则接口收到的就是undefined啦~

注意:对于Axios,响应状态码不是以2开头的都会被认为是失败的;

axios.interceptors.response.use(function (response) {
    // 处理响应code为2开头的响应,如2xx
    return response;
  }, function (error) {
    // 非2xx的响应code皆认为是报错
    return Promise.reject(error);
  });

如果想移除响应拦截器,可以通过:

const myInterceptor = axios.interceptors.response.use(function (config) {/*...*/});
axios.interceptors.response.eject(myInterceptor); // 移除请求拦截器

 若配置多个拦截器(请求或响应都适用),则后指定的拦截器先执行

批量发送请求

可以通过axios.all([ ])实现同时发送多个请求,其本质也是通过Promise.all实现的;

    btn.onclick = () => {
      axios.all([
        axios.get('https://www.baidu.com/'),
        axios.get('https://www.baidu.com/'),
        axios.get('https://www.baidu.com/'),
      ]).then(
        res => { console.log(res, '这是成功的回调') },
        err => { console.log(err, '这是失败的回调') }
      )
    }

取消请求

从v0.22.0开始,axios已经支持AbortController取消请求了:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

补充下axios响应返回的参数如下:

  • data 即后端服务器返回的响应;
  • status 后端服务器响应的HTTP状态码
  • statusText 后端服务器响应的HTTP状态信息
  • headers 后端服务器响应头
  • config 请求配置

axios的二次封装

在实际开发中,往往会根据业务的不同,对原生axios进行二次封装,以下代码可直接拿去使用:

// request.js文件
import axios from 'axios'

// 创建一个axios实例
const request = axios.create({})

// 设置请求拦截器(设置token/loading/baseUrl等)
request.interceptors.request.use((config) => {
    config.baseUrl = '基础路径'
    config.headers['Accept'] = 'application/json;chartset=UTF-8;text-plain,*/*' // 接收哪些类型的参数,前后台定,可不设置,默认是json
    config.headers['authorization'] = '权限' // 根据后台接口定,可无
    config.headers[token] = 'token获取方式' // 一般登录后存到store或storage中
    return config // 记得一定要return出去哦~
}, error => {
    return Promise.reject(error) // return一个状态为rejected的promise,否则默认都是成功
})

// 设置响应拦截器
request.interceptors.response.use((response) => {
    // 响应成功的处理
    if (response.status === 200) {
        return response.data // 也要return出去哦~
    }
}, error => {
    // 响应失败的处理
    return Promise.reject(error)
})

export default request

相关文章:

  • java 设计原则
  • SpringMVC之bean加载控制
  • 【HBase高级】5. HBase数据结构(上)跳表、二叉搜索树、红黑树、B、B+树
  • 你知道那些数字消失了吗?_?
  • C++——继承
  • VisualStudio—Remote Debug
  • python进阶——人工智能实时目标跟踪
  • VUE3.0学习
  • 血氧仪/额温枪/电子体温计等 LED数显/数码管显示驱动控制电路(IC/芯片)-VK1S68C资料 SSO24小体积封装,FAE技术支持
  • 信息系统项目管理师背记精要
  • 【C语言练习】字符串旋转你会嘛?
  • 进阶6 连接查询
  • 用 Python 的 tkinter 模块编写一个好看又强大的中国象棋
  • conda报错 ERROR REPORT Conda has prepared the above report.
  • 一起Talk Android吧(第四百八十四回:使用逐帧动画实现倒计时效果)
  • SpringBoot整合Slf4j+logback日志框架
  • 【数据结构和算法】使用数组的结构实现链表(单向或双向)
  • java 分布式缓存 redis持久化 redis主从 Redis哨兵 Redis分片集群
  • 微服务介绍
  • 【数据结构】ArrayList的具体使用(杨辉三角、扑克牌游戏)
  • 电加热油锅炉工作原理_电加热导油
  • 大型电蒸汽锅炉_工业电阻炉
  • 燃气蒸汽锅炉的分类_大连生物质蒸汽锅炉
  • 天津市维修锅炉_锅炉汽化处理方法
  • 蒸汽汽锅炉厂家_延安锅炉厂家
  • 山西热水锅炉厂家_酒店热水 锅炉
  • 蒸汽锅炉生产厂家_燃油蒸汽发生器
  • 燃煤锅炉烧热水_张家口 淘汰取缔燃煤锅炉
  • 生物质锅炉_炉
  • 锅炉天然气_天燃气热风炉