• axios


    目录

    一 JSON Server使用

     二 介绍

    三 基本使用 

     其他方式发送请求

    创建实例对象

    设置默认配置

    四  axios拦截器

     五 点击取消发送

    六 axios源码分析

    一 JSON Server使用

    第一步

    npm install -g json-server

    第二步:

    创建一个db.json文件并复制如下代码

    1. {
    2. "posts": [
    3. {
    4. "id": 1,
    5. "title": "json-server",
    6. "author": "typicode"
    7. }
    8. ],
    9. "comments": [
    10. {
    11. "id": 1,
    12. "body": "some comment",
    13. "postId": 1
    14. }
    15. ],
    16. "profile": {
    17. "name": "typicode"
    18. }
    19. }

    第三步:

    在终端输入(一定要在db.json目录下输入)

    json-server --watch db.json

                 

     二 介绍

    axios是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

    特性:

    • 从浏览器中发送AJAX请求
    • 在node.js 中发送http请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求数据和响应数据
    • 取消请求
    • 自动将结果转换为JSON 数据
    • 客户端支持阻挡XSRF攻击 

    安装 

    三 基本使用 

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>title>
    8. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js">script>
    9. head>
    10. <body class="container">
    11. <div class= "container">
    12. <h2 class=" page-header" >基本使用h2>
    13. <button class="btn btn-primary"> 发送GET请求 button>
    14. <button cLass="btn btn-warning" > 发送POST请求button>
    15. <button cLass="btn btn-success"> 发送PUT请求button>
    16. <button cLass="btn btn-danger"> 发送DELETE 请求button>
    17. div>
    18. <script>
    19. //获取按钮
    20. const btn=document.querySelectorAll('button');
    21. btn[0].onclick=function(){
    22. //发送AJAX请求
    23. axios({
    24. //请求类型
    25. method:'GET',
    26. //URL
    27. url:'http://localhost:3000/posts',
    28. }).then(response=>{
    29. console.log(response);
    30. })
    31. }
    32. btn[1].onclick=function(){
    33. //发送AJAX请求
    34. axios({
    35. //请求类型
    36. method:'POST',
    37. //URL
    38. url:'http://localhost:3000/posts',
    39. data:{
    40. title:"本天才上线",
    41. author:"张三"
    42. }
    43. }).then(response=>{
    44. console.log(response);
    45. })
    46. }
    47. btn[2].onclick=function(){
    48. //发送AJAX请求
    49. axios({
    50. //请求类型
    51. method:'PUT',
    52. //URL
    53. url:'http://localhost:3000/posts/2',
    54. //设置请求体
    55. data:{
    56. title:"一只猪",
    57. author:"李四"
    58. }
    59. }).then(response=>{
    60. console.log(response);
    61. })
    62. }
    63. btn[3].onclick=function(){
    64. //发送AJAX请求
    65. axios({
    66. //请求类型
    67. method:'delete',
    68. //URL
    69. url:'http://localhost:3000/posts/2',
    70. }).then(response=>{
    71. console.log(response);
    72. })
    73. }
    74. script>
    75. body>
    76. html>

     

     其他方式发送请求

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>title>
    8. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js">script>
    9. head>
    10. <body class="container">
    11. <div class= " container">
    12. <h2 class=" page-header" >基本使用h2>
    13. <button class="btn btn-primary"> 发送GET请求 button>
    14. <button cLass="btn btn-warning" > 发送POST请求button>
    15. div>
    16. <script>
    17. //获取按钮
    18. const btn=document.querySelectorAll('button');
    19. btn[0].onclick=function(){
    20. axios.request({
    21. method:'GET',
    22. url:'http://localhost:3000/comments'
    23. }).then(response=>{
    24. console.log(response);
    25. })
    26. }
    27. //发送POST请求
    28. btn[1].onclick=function(){
    29. axios.post(
    30. 'http://localhost:3000/comments',
    31. {
    32. "body":"喜美cp",
    33. "postId":2
    34. }
    35. ).then(response=>{
    36. console.log(response);
    37. })
    38. }
    39. script>
    40. body>
    41. html>

    创建实例对象

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js">script>
    8. head>
    9. <body class="container">
    10. <div class= "container">
    11. <h2 class="page-header">基本使用h2>
    12. <button class="btn btn-primary"> 发送GET请求 button>
    13. <button cLass="btn btn-warning"> 发送POST请求button>
    14. div>
    15. <script>
    16. //获取按钮
    17. const btn=document.querySelectorAll('button');
    18. //创建实例对象
    19. const xiaohua=axios.create({
    20. baseURL:'http://localhost:3000',
    21. timeout:2000
    22. })
    23. const another=axios.create({
    24. baseURL:'http://b.com',
    25. timeout:2000
    26. })
    27. console.log(xiaohua)
    28. //这里xioahua与axios对象的功能几近相同
    29. /* //用实例对象发送请求第一种方式
    30. xiaohua({
    31. url:'/posts'
    32. }).then(response=>{
    33. console.log(response)
    34. })*/
    35. //第二种方式
    36. xiaohua.get('/posts').then(response=>{
    37. console.log(response.data)
    38. })
    39. script>
    40. body>
    41. html>

    设置默认配置

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>title>
    8. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js">script>
    9. head>
    10. <body>
    11. <button class="btn">点击button>
    12. <script>
    13. const btn=document.querySelector('button')
    14. //默认配置
    15. axios.defaults.method = 'GET' ;//设置默认的请求类型为GET
    16. axios.defaults.baseURL = 'http://localhost:3000' ;//设置基础URL
    17. axios.defaults.params = {id:100};//params 即将与请求一起发送的 URL 参数
    18. axios.defaults.timeout = 3000;// axios.post(url[, data[, config]])
    19. btn.onclick=function(){
    20. axios({
    21. url:'/posts'
    22. }).then(response=>{
    23. console.log(response)
    24. })
    25. }
    26. script>
    27. body>
    28. html>

    四  axios拦截器

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>拦截器title>
    8. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js">script>
    9. head>
    10. <body>
    11. <script>
    12. //设置请求拦截器 config配置对象
    13. axios.interceptors.request.use(function(config){
    14. console.log('请求拦截器成功 1号')
    15. config.params={a:100}
    16. return config;
    17. // throw '参数处了问题'
    18. },function(error){
    19. console.log('请求拦截器失败 1号')
    20. return Promise.reject(error);
    21. })
    22. axios.interceptors.request.use(function(config){
    23. console.log('请求拦截器成功 2号')
    24. config.params={a:100}
    25. return config;
    26. //throw '参数处了问题'
    27. },function(error){
    28. console.log('请求拦截器失败 2号')
    29. return Promise.reject(error);
    30. })
    31. axios.interceptors.response.use(function(response){
    32. console.log('响应拦截器成功 1号')
    33. return response.data;
    34. },function(error){
    35. console.log('响应拦截器失败 1号')
    36. return Promise.reject(error);
    37. })
    38. axios.interceptors.response.use(function(response){
    39. console.log('响应拦截器成功 2号')
    40. return response;
    41. },function(error){
    42. console.log('响应拦截器失败 2号')
    43. return Promise.reject(error);
    44. })
    45. //发送请求
    46. axios({
    47. method:'GET',
    48. url:'http://localhost:3000/posts'
    49. }).then(response=>{
    50. console.log('自定义回调处理成功')
    51. console.log(response)
    52. }).catch(reason=>{
    53. console.log('自定义回调失败')
    54. })
    55. script>
    56. body>
    57. html>

    1.请求拦截器:
    在真正发送请求前执行的回调函数
    可以对请求进行检查或配置进行特定处理
    成功的回调函数,传递的默认是config(也必须是)
    失败的回调函数,传递的默认是error
     2 响应拦截器

    在请求得到响应后执行的回调函数
    可以对响应数据进行特定处理
    成功的回调函数,传递的默认是response
    失败的回调函数,传递的默认是error
     

     五 点击取消发送

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>点击取消请求title>
    8. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js">script>
    9. head>
    10. <body>
    11. <button class="btn">点击发送请求button>
    12. <button class="btn">点击取消请求button>
    13. <script>
    14. const btns=document.querySelectorAll('button')
    15. //2.声明全局变量
    16. let cancel=null;
    17. btns[0].onclick=function(){
    18. //检测上一次请求是否完成
    19. if(cancel!==null){
    20. //取消上一次请求
    21. cancel()
    22. }
    23. axios({
    24. method:'GET',
    25. url:'http://localhost:3000/posts',
    26. //1.添加配置对象的属性
    27. cancelToken:new axios.CancelToken(function(c){
    28. cancel=c
    29. })
    30. }).then(response=>{
    31. cancel=null
    32. console.log(response)
    33. })
    34. }
    35. btns[1].onclick=function(){
    36. cancel();
    37. }
    38. script>
    39. body>
    40. html>

    六 axios源码分析

    (1)axios与Axios关系

      1)从语法上来说:axios不是Axios的实例
      2)从功能上来说:axios是Axios的实例
      3)axios 是Axios.prototype.request函数bind()返回的函数
      4)axios 作为对象有Axios原型对象上的所有方法,有Axios对象上所有属性

    (2)instance与axios的区别?
    相同:
      1)都是一个能发任意请求的函数: request(config)
      2)都有发特定请求的各种方法: get()/post()/ put()/delete()
      3)都有默认配置和拦截器的属性: defaults/interceptors
    不同:
      1)默认配置很可能不一样
      2) instance 没有axios后面添加的一些方法: create()/CancelToken()/all()

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

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

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

    (4)response整体结构:{data,status,statusText,headers,config,request}
         error整体结构:{message,response,request}

    (5)如何取消未完成的请求?
     1.当配置 了cancelToken对象时,保存cancel函数
          1) 创建一个用于将来中断请求的cancelPromise
           2) 并定义了一个用于取消请求的cancel函数
          3)将cancel函数传递出来
    2.调用 cancel()取消请求
         1) 执行cacel函数,传入错误信息message
          2)内部会让cancelPromise变为成功,且成功的值为-个Cancel对象
          3)在cancelPromise的成功回调中中断请求,并让发请求的proimse失败,失败的reason为  Cancel 对象
     

  • 相关阅读:
    基于线性回归根据饮食习惯和身体状况估计肥胖水平
    帮扶、提振、担当,第六届土巴兔718全民家装节的新价值和意义
    12.SpringBoot之RestTemplate的使用
    (四) Python 使用Pandas生成日报
    07_用队列实现栈
    vscode和HBuilderx设置快捷键注释
    阿里云服务器的优点与缺点分析!!
    Hyperledger Fabric Transaction Flow——事务处理流程
    2023年中国电子白板市场规模、竞争格局及应用领域市场结构[图]
    第三方支付功能测试点【杭州多测师_王sir】【杭州多测师】
  • 原文地址:https://blog.csdn.net/qq_62401904/article/details/126195678