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

<body>
    <h2>基本使用</h2>
    <div>
        <button onclick="getGet()">发送GET请求</button>
        <button onclick="getPost()">发送POST请求</button>
        <button onclick="getPUT()">发送PUT请求</button>
        <button onclick="getDelete()">发送DELETE</button>
    </div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</script>
<script>
    // get请求
    function getGet(){
        axios({
        url:'http://localhost:3000/posts/1'
    }).then(res=>{
        console.log(res.data)
    })
    };
    // Post请求
    function getPost(){
        axios({
            url:'http://localhost:3000/posts',
            // 设置请求体
            data:{
                title:"今天的天气还不错,挺风和日丽的",
                author:"张三"
​
            },
            method:'POST'
        }).then(res=>{
            console.log(res)
        })
​
    };
    // 更新 数据
    function getPUT(){
        axios({
            method:'put',
            url:'http://localhost:3000/posts/3',
            data:{
                title:'今天的天气还不错,挺风和日丽的',
                author:"李四",
                
            }
            
        }).then(res=>{
            console.log(res)
        })
    };
    // 删除数据
    function getDelete(){
        axios({
            method:'delete',
            url:'http://localhost:3000/posts/5'
​
        }).then(res=>{
            console.log(res)
        })
    }
​
    
</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]])

<body>
    <h2>axios的其他方式发松请求</h2>
   
    <div>
        <button onclick="getRequest()">axios的request</button>
        <button onclick="getPostUrl()">axios的Post</button>
    </div>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</script>
<script>
 
    // ---------------------axios的其他方式发送请求---------------------
    // request
    function getRequest(){
        axios.request({
            method:'get',
            url:'http://localhost:3000/posts',
​
        }).then(res=>{
            console.log(res.data)
        })
    }
// 发送post请求
// axios.post(url,data,config).then(res=>{})
    function getPostUrl(){
        axios.post('http://localhost:3000/posts',{
            "title":"嘿嘿把 烦恼摇出来",
                "author":"没烦恼"
        }).then(res=>{
            console.log(res)
        })
    }
</script>

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

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

五、axios配置对象详细说明

{
   // `url` 是用于请求的服务器 URL
  url: '/user',
​
  // `method` 是创建请求时使用的方法
  method: 'get', // default
​
  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',
​
  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data, headers) {
    // 对 data 进行任意转换处理
    return data;
  }],
​
  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],
​
  // `headers` 是即将被发送的自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},
​
  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },
​
   // `paramsSerializer` 是一个负责 `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` 是作为请求主体被发送的数据
  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // - Node 专属: Stream
  data: {
    firstName: 'Fred'
  },
​
  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,
​
   // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // default
​
  // `adapter` 允许自定义处理请求,以使测试更轻松
  // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },
​
 // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
​
   // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default
​
  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default
​
   // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  xsrfCookieName: 'XSRF-TOKEN', // default
​
  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default
​
   // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
​
  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },
​
   // `maxContentLength` 定义允许的响应内容的最大尺寸
  maxContentLength: 2000,
​
  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },
​
  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  // 如果设置为0,将不会 follow 任何重定向
  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` 和 `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
  // (查看后面的 Cancellation 这节了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}
 

六、axios的默认配置

配置默认值

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

全局的 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';

实践:

  
 // ---------------------axios的默认配置---------------------------
    function getDefault(){
        axios.defaults.method='get'; //设置默认的请求类型
        axios.defaults.baseURL='http://localhost:3000';
        axios({
            url:'/posts'
        }).then(res=>{
            console.log(res)
        })
    }

自定义实例默认值

// 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;

配置的优先顺序

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

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

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

创建实例

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

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

实践:

    
    // 创建axios的实例 好处在于:可以发起两个不同的请求。简写默认配置。
    const mingyan=axios.create({
        baseURL:'https://api.apiopen.top/api',
        timeout:2000
    });
     //写法一
     mingyan({
         url:'/sentences',

     }).then(res=>{
         console.log(res)
     })
    // 写法二
    mingyan.get('/sentences').then(res=>{
        console.log(res.data)
    })

实例方法

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

  • 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 处理前拦截它们。

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
​
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

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

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

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

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

实践:

   // ------------------axios的拦截器---------------
    // Promise
    // 添加请求拦截器
axios.interceptors.request.use(function (config) {
    console.log('请求拦截器 成功  1号')
    // 修改config中的参数
    config.params={a:100};
    return config;
    // throw '参数出了问题'
  }, function (error) {
    console.log('请求拦截器 失败 1号')
    return Promise.reject(error);
  });
  axios.interceptors.request.use(function (config) {
    console.log('请求拦截器 成功  2号')
      // 修改config中的参数
      config.timeout=2000;
    return config;
    // throw '参数出了问题'
  }, function (error) {
    console.log('请求拦截器 失败 2号')
    return Promise.reject(error);
  });
​
​
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    console.log("响应拦截器 成功 1号")
// 设置之后,会处理发起请求中返回的结果,只有data了
    return response.data;
  }, function (error) {
    console.log("响应拦截器 失败 1号")
    return Promise.reject(error);
  });
  // 添加响应拦截器
axios.interceptors.response.use(function (response) {
    console.log("响应拦截器 成功 2号")
    return response;
  }, function (error) {
    console.log("响应拦截器 失败 2号")
    return Promise.reject(error);
  });
//   发起请求
  axios({
      method:'get',
      url:'/posts',
      baseURL:'http://localhost:3000'
  }).then(res=>{
      console.log("--------------")
      console.log(res)
  }).catch(resp=>{
      console.log("自定义失败回调")
  })

九、axios取消请求

取消cancel token

使用 cancel token 取消请求

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

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

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 {
     // 处理错误
  }
});
​
axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})
​
// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

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

const CancelToken = axios.CancelToken;
let cancel;
​
axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  })
});
​
// cancel the request
cancel();

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

实践:

//--------------html----------
 <div>
        <button onclick="getposts()">发起请求</button>
        <button onclick="cancelRequest()">取消请求</button>
    </div>
//-------------js---------------
//   ------------------取消请求----------------
// 声明全局变量
let cancel=null;
// 发起请求
function getposts(){
    // 检测上一次的请求是否已经完成
    if(cancel !== null){
        // 未完成 取消请求
        cancel();
    }
    axios({
        method:'get',
        url:'/comments',
        baseURL:'http://localhost:3000',
        // 添加配置对象 的属性
        cancelToken: new axios.CancelToken(function(c){
            // 将c的值赋值给cancal
            cancel=c;
​
        })
​
        }).then(response=>{
            console.log(response)
            // 将cancel的值初始化
            cancel=null
​
        })
    
}
// 取消请求
function cancelRequest(){
    cancel();
}
注意:要设置json-server --watch db.json -d 2000 超时2秒返回结果,不然取消不了请求

十、axios的文件结构

├── /dist/ # 项目输出目录
​
├── /lib/ # 项目源码目录
​
│ 
​
├── /adapters/ # 定义请求的适配器 xhr、http
​
│ 
​
│ 
​
├── http.js # 实现 http 适配器(包装 http 包)
​
│ 
​
│ 
​
└── **xhr.js #** **实现** **xhr** **适配器****(****包装** **xhr** **对象****)**
​
│ 
​
├── /cancel/ # 定义取消功能
​
│ 
​
├── /core/ # 一些核心功能
​
│ 
​
│ 
​
├── **Axios.js # axios** **的核心主类**
​
│ 
​
│ 
​
├── **dispatchRequest.js #** **用来调用** **http** **请求适配器方法发送请求的函数**
​
│ 
​
│ 
​
├── InterceptorManager.js # 拦截器的管理器
​
│ 
​
│ 
​
└── settle.js # 根据 http 响应状态,改变 Promise 的状态
​
│ 
​
├── /helpers/ # 一些辅助方法
​
│ 
​
├── axios.js # 对外暴露接口
​
│ 
​
├── **defaults.js # axios** **的默认配置**
​
│ 
​
└── utils.js # 公用工具
​
├── package.json # 项目信息
​
├── index.d.ts # 配置 TypeScript 的声明文件
​
└── 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 对象

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值