当前位置:   article > 正文

axios教程_axios 方法 教程

axios 方法 教程

一、axios的安装方式

使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、axios的基本使用

get、post、put、delete

  1. <body>
  2.    <h2>基本使用</h2>
  3.    <div>
  4.        <button onclick="getGet()">发送GET请求</button>
  5.        <button onclick="getPost()">发送POST请求</button>
  6.        <button onclick="getPUT()">发送PUT请求</button>
  7.        <button onclick="getDelete()">发送DELETE</button>
  8.    </div>
  9. </body>
  10. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  11. </script>
  12. <script>
  13.    // get请求
  14.    function getGet(){
  15.        axios({
  16.        url:'http://localhost:3000/posts/1'
  17.   }).then(res=>{
  18.        console.log(res.data)
  19.   })
  20.   };
  21.    // Post请求
  22.    function getPost(){
  23.        axios({
  24.            url:'http://localhost:3000/posts',
  25.            // 设置请求体
  26.            data:{
  27.                title:"今天的天气还不错,挺风和日丽的",
  28.                author:"张三"
  29.           },
  30.            method:'POST'
  31.       }).then(res=>{
  32.            console.log(res)
  33.       })
  34.   };
  35.    // 更新 数据
  36.    function getPUT(){
  37.        axios({
  38.            method:'put',
  39.            url:'http://localhost:3000/posts/3',
  40.            data:{
  41.                title:'今天的天气还不错,挺风和日丽的',
  42.                author:"李四",
  43.                
  44.           }
  45.            
  46.       }).then(res=>{
  47.            console.log(res)
  48.       })
  49.   };
  50.    // 删除数据
  51.    function getDelete(){
  52.        axios({
  53.            method:'delete',
  54.            url:'http://localhost:3000/posts/5'
  55.       }).then(res=>{
  56.            console.log(res)
  57.       })
  58.   }
  59.    
  60. </script>

三、axios其他方式发送请求

axios请求方法别名

  • 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.request(config) 和 axios.post(url[,data[,config]])

  1. <body>
  2.    <h2>axios的其他方式发松请求</h2>
  3.  
  4.    <div>
  5.        <button onclick="getRequest()">axios的request</button>
  6.        <button onclick="getPostUrl()">axios的Post</button>
  7.    </div>
  8. </body>
  9. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  10. </script>
  11. <script>
  12.    // ---------------------axios的其他方式发送请求---------------------
  13.    // request
  14.    function getRequest(){
  15.        axios.request({
  16.            method:'get',
  17.            url:'http://localhost:3000/posts',
  18.       }).then(res=>{
  19.            console.log(res.data)
  20.       })
  21.   }
  22. // 发送post请求
  23. // axios.post(url,data,config).then(res=>{})
  24.    function getPostUrl(){
  25.        axios.post('http://localhost:3000/posts',{
  26.            "title":"嘿嘿把 烦恼摇出来",
  27.                "author":"没烦恼"
  28.       }).then(res=>{
  29.            console.log(res)
  30.       })
  31.   }
  32. </script>

四、axios请求响应结果的结构

  • config:配置对象,包含请求类型,请求url,请求体
  • data:响应体的结果。返回的数据,axios自动将json数据转化为对象
  • headers:响应头的信息
  • request:保存的是axios发送请求创建的原生的ajax对象
  • status:响应的状态
  • statusText:响应的状态字符串

五、axios配置对象详细说明

  1. {
  2.   // `url` 是用于请求的服务器 URL
  3.  url: '/user',
  4.  // `method` 是创建请求时使用的方法
  5.  method: 'get', // default
  6.  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  7.  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  8.  baseURL: 'https://some-domain.com/api/',
  9.  // `transformRequest` 允许在向服务器发送前,修改请求数据
  10.  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  11.  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  12.  transformRequest: [function (data, headers) {
  13.    // 对 data 进行任意转换处理
  14.    return data;
  15. }],
  16.  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  17.  transformResponse: [function (data) {
  18.    // 对 data 进行任意转换处理
  19.    return data;
  20. }],
  21.  // `headers` 是即将被发送的自定义请求头
  22.  headers: {'X-Requested-With': 'XMLHttpRequest'},
  23.  // `params` 是即将与请求一起发送的 URL 参数
  24.  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  25.  params: {
  26.    ID: 12345
  27. },
  28.   // `paramsSerializer` 是一个负责 `params` 序列化的函数
  29.  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  30.  paramsSerializer: function(params) {
  31.    return Qs.stringify(params, {arrayFormat: 'brackets'})
  32. },
  33.  // `data` 是作为请求主体被发送的数据
  34.  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  35.  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  36.  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  37.  // - 浏览器专属:FormData, File, Blob
  38.  // - Node 专属: Stream
  39.  data: {
  40.    firstName: 'Fred'
  41. },
  42.  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  43.  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  44.  timeout: 1000,
  45.   // `withCredentials` 表示跨域请求时是否需要使用凭证
  46.  withCredentials: false, // default
  47.  // `adapter` 允许自定义处理请求,以使测试更轻松
  48.  // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  49.  adapter: function (config) {
  50.    /* ... */
  51. },
  52. // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  53.  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  54.  auth: {
  55.    username: 'janedoe',
  56.    password: 's00pers3cret'
  57. },
  58.   // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  59.  responseType: 'json', // default
  60.  // `responseEncoding` indicates encoding to use for decoding responses
  61.  // Note: Ignored for `responseType` of 'stream' or client-side requests
  62.  responseEncoding: 'utf8', // default
  63.   // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  64.  xsrfCookieName: 'XSRF-TOKEN', // default
  65.  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  66.  xsrfHeaderName: 'X-XSRF-TOKEN', // default
  67.   // `onUploadProgress` 允许为上传处理进度事件
  68.  onUploadProgress: function (progressEvent) {
  69.    // Do whatever you want with the native progress event
  70. },
  71.  // `onDownloadProgress` 允许为下载处理进度事件
  72.  onDownloadProgress: function (progressEvent) {
  73.    // 对原生进度事件的处理
  74. },
  75.   // `maxContentLength` 定义允许的响应内容的最大尺寸
  76.  maxContentLength: 2000,
  77.  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
  78.  validateStatus: function (status) {
  79.    return status >= 200 && status < 300; // default
  80. },
  81.  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  82.  // 如果设置为0,将不会 follow 任何重定向
  83.  maxRedirects: 5, // default
  84.  // `socketPath` defines a UNIX Socket to be used in node.js.
  85.  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  86.  // Only either `socketPath` or `proxy` can be specified.
  87.  // If both are specified, `socketPath` is used.
  88.  socketPath: null, // default
  89.  // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
  90.  // `keepAlive` 默认没有启用
  91.  httpAgent: new http.Agent({ keepAlive: true }),
  92.  httpsAgent: new https.Agent({ keepAlive: true }),
  93.  // 'proxy' 定义代理服务器的主机名称和端口
  94.  // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
  95.  // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
  96.  proxy: {
  97.    host: '127.0.0.1',
  98.    port: 9000,
  99.    auth: {
  100.      username: 'mikeymike',
  101.      password: 'rapunz3l'
  102.   }
  103. },
  104.  // `cancelToken` 指定用于取消请求的 cancel token
  105.  // (查看后面的 Cancellation 这节了解更多)
  106.  cancelToken: new CancelToken(function (cancel) {
  107. })
  108. }
 

六、axios的默认配置

配置默认值

你可以指定将被用在各个请求的配置默认值

全局的 axios 默认值

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

实践:

  
  1. // ---------------------axios的默认配置---------------------------
  2.    function getDefault(){
  3.        axios.defaults.method='get'; //设置默认的请求类型
  4.        axios.defaults.baseURL='http://localhost:3000';
  5.        axios({
  6.            url:'/posts'
  7.       }).then(res=>{
  8.            console.log(res)
  9.       })
  10.   }

自定义实例默认值

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

配置的优先顺序

配置会以一个优先顺序进行合并。这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者。这里是一个例子:

  1. // 使用由库提供的配置的默认值来创建实例
  2. // 此时超时配置的默认值是 `0`
  3. var instance = axios.create();
  4. // 覆写库的超时默认值
  5. // 现在,在超时前,所有请求都会等待 2.5 秒
  6. instance.defaults.timeout = 2500;
  7. // 为已知需要花费很长时间的请求覆写超时设置
  8. instance.get('/longRequest', {
  9.  timeout: 5000
  10. });

七、axios创建实例对象发送请求

创建实例

可以使用自定义配置新建一个 axios 实例

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

实践:

    
  1. // 创建axios的实例 好处在于:可以发起两个不同的请求。简写默认配置。
  2. const mingyan=axios.create({
  3. baseURL:'https://api.apiopen.top/api',
  4. timeout:2000
  5. });
  6. //写法一
  7. mingyan({
  8. url:'/sentences',
  9. }).then(res=>{
  10. console.log(res)
  11. })
  12. // 写法二
  13. mingyan.get('/sentences').then(res=>{
  14. console.log(res.data)
  15. })

实例方法

以下是可用的实例方法。指定的配置将与实例的配置合并。

  • 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的拦截器

拦截器Interceptors

在请求或响应被 thencatch 处理前拦截它们。

  1. // 添加请求拦截器
  2. axios.interceptors.request.use(function (config) {
  3.    // 在发送请求之前做些什么
  4.    return config;
  5. }, function (error) {
  6.    // 对请求错误做些什么
  7.    return Promise.reject(error);
  8. });
  9. // 添加响应拦截器
  10. axios.interceptors.response.use(function (response) {
  11.    // 对响应数据做点什么
  12.    return response;
  13. }, function (error) {
  14.    // 对响应错误做点什么
  15.    return Promise.reject(error);
  16. });

如果你想在稍后移除拦截器,可以这样:

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

可以为自定义 axios 实例添加拦截器

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

实践:

  1.   // ------------------axios的拦截器---------------
  2.    // Promise
  3.    // 添加请求拦截器
  4. axios.interceptors.request.use(function (config) {
  5.    console.log('请求拦截器 成功 1号')
  6.    // 修改config中的参数
  7.    config.params={a:100};
  8.    return config;
  9.    // throw '参数出了问题'
  10. }, function (error) {
  11.    console.log('请求拦截器 失败 1号')
  12.    return Promise.reject(error);
  13. });
  14.  axios.interceptors.request.use(function (config) {
  15.    console.log('请求拦截器 成功 2号')
  16.      // 修改config中的参数
  17.      config.timeout=2000;
  18.    return config;
  19.    // throw '参数出了问题'
  20. }, function (error) {
  21.    console.log('请求拦截器 失败 2号')
  22.    return Promise.reject(error);
  23. });
  24. // 添加响应拦截器
  25. axios.interceptors.response.use(function (response) {
  26.    console.log("响应拦截器 成功 1号")
  27. // 设置之后,会处理发起请求中返回的结果,只有data了
  28.    return response.data;
  29. }, function (error) {
  30.    console.log("响应拦截器 失败 1号")
  31.    return Promise.reject(error);
  32. });
  33.  // 添加响应拦截器
  34. axios.interceptors.response.use(function (response) {
  35.    console.log("响应拦截器 成功 2号")
  36.    return response;
  37. }, function (error) {
  38.    console.log("响应拦截器 失败 2号")
  39.    return Promise.reject(error);
  40. });
  41. //   发起请求
  42.  axios({
  43.      method:'get',
  44.      url:'/posts',
  45.      baseURL:'http://localhost:3000'
  46. }).then(res=>{
  47.      console.log("--------------")
  48.      console.log(res)
  49. }).catch(resp=>{
  50.      console.log("自定义失败回调")
  51. })

九、axios取消请求

取消cancel token

使用 cancel token 取消请求

Axios 的 cancel token API 基于cancelable promises proposal,它还处于第一阶段。

可以使用 CancelToken.source 工厂方法创建 cancel token,像这样:

  1. const CancelToken = axios.CancelToken;
  2. const source = CancelToken.source();
  3. axios.get('/user/12345', {
  4.  cancelToken: source.token
  5. }).catch(function(thrown) {
  6.  if (axios.isCancel(thrown)) {
  7.    console.log('Request canceled', thrown.message);
  8. } else {
  9.     // 处理错误
  10. }
  11. });
  12. axios.post('/user/12345', {
  13.  name: 'new name'
  14. }, {
  15.  cancelToken: source.token
  16. })
  17. // 取消请求(message 参数是可选的)
  18. source.cancel('Operation canceled by the user.');

还可以通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token:

  1. const CancelToken = axios.CancelToken;
  2. let cancel;
  3. axios.get('/user/12345', {
  4.  cancelToken: new CancelToken(function executor(c) {
  5.    // executor 函数接收一个 cancel 函数作为参数
  6.    cancel = c;
  7. })
  8. });
  9. // cancel the request
  10. cancel();

注意: 可以使用同一个 cancel token 取消多个请求

实践:

  1. //--------------html----------
  2. <div>
  3.        <button onclick="getposts()">发起请求</button>
  4.        <button onclick="cancelRequest()">取消请求</button>
  5.    </div>
  6. //-------------js---------------
  7. //   ------------------取消请求----------------
  8. // 声明全局变量
  9. let cancel=null;
  10. // 发起请求
  11. function getposts(){
  12.    // 检测上一次的请求是否已经完成
  13.    if(cancel !== null){
  14.        // 未完成 取消请求
  15.        cancel();
  16.   }
  17.    axios({
  18.        method:'get',
  19.        url:'/comments',
  20.        baseURL:'http://localhost:3000',
  21.        // 添加配置对象 的属性
  22.        cancelToken: new axios.CancelToken(function(c){
  23.            // 将c的值赋值给cancal
  24.            cancel=c;
  25.       })
  26.       }).then(response=>{
  27.            console.log(response)
  28.            // 将cancel的值初始化
  29.            cancel=null
  30.       })
  31.    
  32. }
  33. // 取消请求
  34. function cancelRequest(){
  35.    cancel();
  36. }
注意:要设置json-server --watch db.json -d 2000 超时2秒返回结果,不然取消不了请求

十、axios的文件结构

  1. ├── /dist/ # 项目输出目录
  2. ├── /lib/ # 项目源码目录
  3. ├── /adapters/ # 定义请求的适配器 xhr、http
  4. ├── http.js # 实现 http 适配器(包装 http 包)
  5. └── **xhr.js #** **实现** **xhr** **适配器****(****包装** **xhr** **对象****)**
  6. ├── /cancel/ # 定义取消功能
  7. ├── /core/ # 一些核心功能
  8. ├── **Axios.js # axios** **的核心主类**
  9. ├── **dispatchRequest.js #** **用来调用** **http** **请求适配器方法发送请求的函数**
  10. ├── InterceptorManager.js # 拦截器的管理器
  11. └── settle.js # 根据 http 响应状态,改变 Promise 的状态
  12. ├── /helpers/ # 一些辅助方法
  13. ├── axios.js # 对外暴露接口
  14. ├── **defaults.js # axios** **的默认配置**
  15. └── utils.js # 公用工具
  16. ├── package.json # 项目信息
  17. ├── index.d.ts # 配置 TypeScript 的声明文件
  18. └── index.js # 入口文件

十一、axios的创建过程

axios 与 Axios 的关系 ?

  1. 从语法上来说: axios 不是 Axios 的实例

  2. 从功能上来说: axios 是 Axios 的实例

  3. axios 是 Axios.prototype.request 函数 bind()返回的函数

  4. axios 作为对象有 Axios 原型对象上的所有方法, 有 Axios 对象上所有属性

instance 与 axios 的区别?

  1. 相同:

(1) 都是一个能发任意请求的函数: request(config)

(2) 都有发特定请求的各种方法: get()/post()/put()/delete()

(3) 都有默认配置和拦截器的属性: defaults/interceptors

  1. 不同:

(1) 默认配置很可能不一样

(2) instance 没有 axios 后面添加的一些方法: create()/CancelToken()/all()

十二、axios的运行过程

1. 整体流程:

request(config) ==> dispatchRequest(config) ==> xhrAdapter(config)

2. request(config):

将请求拦截器 / dispatchRequest() / 响应拦截器 通过 promise 链串连起来,

返回 promise

3. dispatchRequest(config):

转换请求数据 ===> 调用 xhrAdapter()发请求 ===> 请求返回后转换响应数

据.

返回 promise

4. xhrAdapter(config):

创建 XHR 对象, 根据 config 进行相应设置, 发送特定请求, 并接收响应数据,

返回 promise

十三、axios 的请求响应拦截器是什么?

axios 的请求过程?

1. 请求转换器: 对请求头和请求体数据进行特定处理的函数

if (utils.isObject(data)) {

setContentTypeIfUnset(headers, 'application/json;charset=utf-8');

return JSON.stringify(data);

}

2. 响应转换器: 将响应体 json 字符串解析为 js 对象或数组的函数

response.data = JSON.parse(response.data)

response 的整体结构

{

data,

status,

statusText,

headers,

config,

request

}

error 的整体结构

{

message,

response,

request,

}

如何取消未完成的请求?

1. 当配置了 cancelToken 对象时, 保存 cancel 函数

(1) 创建一个用于将来中断请求的 cancelPromise

(2) 并定义了一个用于取消请求的 cancel 函数

(3) 将 cancel 函数传递出来

2. 调用 cancel()取消请求

(1) 执行 cacel 函数, 传入错误信息 message

(2) 内部会让 cancelPromise 变为成功, 且成功的值为一个 Cancel 对象

(3) 在 cancelPromise 的成功回调中中断请求, 并让发请求的 proimse 失败,

失败的 reason 为 Cancel 对象

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/784006
推荐阅读
相关标签
  

闽ICP备14008679号