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

React:Axios

axios可以在浏览器和node.js两边跑,可以向服务端发起ajax请求,也可以在node.js里运行,向远端服务发送http请求

Axios中文文档 | Axios中文网

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<script src="https://unpkg.com/axios@1.6.7/dist/axios.min.js"></script>

</head>
<body>
    <script>
        console.log(axios)
        
    </script>
</body>
</html>

获取失败了,报错404了

查了半夜发现前后端端口号不同涉嫌跨域(CORS)问题,此时要么修改前端,要么修改后端,消除跨域问题

我选择了把二者端口号改成一样的,就不跨域了

json-server --watch db.json --port 8080

好了,现在变成这样了,报错还是404

GPT用它最后的波纹告诉我,用liver server,会自动帮我运行一个静态服务器

再把后端端口号改为和前端一样的就好了

这么重要的东西为什么没人说!!

axiosAPI接口

axios(配置)
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>axios基本使用</title>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary"> 发送GET请求 </button>
        <button class="btn btn-warning" > 发送POST请求 </button>
        <button class="btn btn-success"> 发送 PUT 请求 </button>
        <button class="btn btn-danger"> 发送 DELETE 请求 </button>
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
        //第一个按钮
btns[0].onclick=function(){
    //发送ajax请求
    axios(
        {
            //请求类型:GET
            method:'GET',
            //请求URL,注意端口号
            url:'http://localhost:52896'
        }).then(reponse=>{
            console.log(reponse)
            
        })
   
}
    </script>
</body>

</html>

点击get发送请求

axios是基于promise的,他的每个请求(如 getpostput 等)都返回一个promise,因为直接返回的是一个promise,所以后面可以直接接then来处理成功/失败的回调函数

axios请求成功后,会将服务器的响应封装成一个 响应对象,并传递给 .then() 的回调函数。

然后把reponse当作一个axios封装的响应对象做为参数传入回调函数内

可以看见异步请求成功

为什么我的打开里面不是数据

原来是我的url错了

这下对了

如果在浏览器里一闪就过去了,需要在浏览器保留日志

axios就像封装了ajax的promise

请求方法别名

为方便起见,已为所有常见的请求方法提供了别名。

axios.request(config)

  btns[0].onclick=function(){ 
    axios.request({
        method:'GET',
        url:'http://localhost:52896/comments'
    }).then(response=>{
        console.log(response)
    })
}

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

data为请求体,config是可选选项

btns[1].onclick=function(){
    axios.post(
        'http://localhost:52896/comments',
      {"body": "喜大普奔",
      "postId": 2
    }
).then(response=>{
        console.log(response)
    })
}

axios响应对象

每次发送请求,就会返回一个axios响应对象,这是它的具体结构

config是配置对象 ,里面包含了请求类型,请求url,请求体

data是响应体,也就是服务器返回的结果

data为什么是个对象?是因为axios自动将返回的json转为对象,方便对结果进行处理

headers是相应的头信息

request保存的是原生的Ajax请求对象 ,axios发送Ajax请求需要用到XMLHttpRequest

毕竟官网说了👇

Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests

下面的200是响应的状态码,OK是响应的状态字符串

Config

一些配置对象的说明

{
  //url是指明请求要发给谁,完整的请求地址
  url: '/user',

  // 设置请求类型
  method: 'get', 

 // 设定url的基础结构,也就是请求的根路径
 //axios内部会自动将url和baseURL做结合,获取最终的url结果

 //简化请求路径,可以只写后面的路径,不用写域名和协议
  baseURL: 'https://some-domain.com/api/',


  //对请求的数据做处理,向服务器发送处理后的结果
  transformRequest: [function (data, headers) {
    return data;
  }],

  //也是对请求的数据做处理,发送给服务器处理后的结果
    transformResponse: [function (data) {
    return data;
  }],

 //配置请求头信息,在某些项目进行身份校验,可以在头信息里进行配置
  headers: {'X-Requested-With': 'XMLHttpRequest'},

//是一个对象,可以将数据以查询参数的形式附加到url里
//未使用 params 的 URL: https://api.example.com/data
//使用 params 的 URL: https://api.example.com/data?name=John&age=30
params: {
    ID: 12345
  },

//参数序列化的配置项,用的相对较少,对请求的参数做序列化,将 params 对象转换为 URL 查询字符串
 paramsSerializer: {
    encode?: (param: string): string => {  }, 
    serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), 
    indexes: false  
  },

//超时时间
 timeout: 1000, 
//跨域请求时是否携带cookie
 withCredentials: false,

//对请求设置,一种是ajax,一种是在node.js里发送http
  adapter: function (config) {
    /* ... */
  },

//设置用户名和密码,对请求基础验证
 auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

//对响应体类型的设置,默认是json,在返回的时候从json会转为对象
responseType: 'json',

//响应结果的编码
 responseEncoding: 'utf8',

//跨域请求,对cookie的名字进行设置
xsrfCookieName: 'XSRF-TOKEN',

//设置头信息
xsrfHeaderName: 'X-XSRF-TOKEN',

//安全设置,保证请求来自自己的客户端,保护作用
 withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),

//上传的时候进行回调
onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
  },

//下载的时候进行回调 
 onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
  },

//设置http响应的最大尺寸
maxContentLength: 2000,

//设置请求体的最大尺寸
  maxBodyLength: 2000,

//对响应结果的成功做设置
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

//最大跳转次数,向一个服务发起请求后要跳转,做完跳转是否要继续请求的次数限制
//一般用在node.js里,ajax里用不到
maxRedirects: 21, //默认值

//
  beforeRedirect: (options, { headers }) => {
    if (options.hostname === "example.com") {
      options.auth = "user:password";
    }
  },
//设置socket文件的位置
socketPath: null, 

//很有用,设置代理,用在服务端
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    // hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

//对ajax请求取消
  cancelToken: new CancelToken(function (cancel) {
  }),

//对响应结果是否做解压,默认解压,ajax用不了,在node用
decompress: true, // default

//httpAgent是对客户端连接的设置
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),


}

axios的默认配置

把重复的设置配在默认里,简化代码

比如配置默认路径,url可以不用写这么长;配置默认请求

      axios.default.method='GET'//设置默认的请求类型为GET
        axios.default.baseURL='http://localhost:52896'

设置默认params,把id加到url后面

        axios.defaults.params={id:100}
        axios.defaults.timout=3000

 axios创建实例对象发送ajax请求

axios.create()来实例化

        //获取按钮
        const btns = document.querySelectorAll('button')
        //创建实例对象
const duanzi=axios.create(
    {
        baseURL:'https//api.apiopen.top',
        timeout:2000
    }
)
//这里duanzi与axios对象功能几近是一样的
console.log(duanzi)

打印到控制台

//拿duanzi当axios使用,因为他是axios的实例化对象
duanzi({
    url:'/getJoke',
}).then(reponse=>{
    console.log(reponse)
})

用实例对象使用请求方法

duanzi.get('/getJoke').then(response=>{
    console.log(response.data)
})

如果有跨域的问题,例如我们的项目如果不是来源单一的服务器,就可以创建两个对象

const duanzi=axios.create(
    {
        baseURL:'https://api.apiopen.top',
        timeout:2000
    }
)
const another=axios.create({
    baseURL:'https://b.cm',
    timeout:2000
})

拦截器

拦截器的本质是一些函数

拦截器分为请求拦截器和响应拦截器

请求拦截器可以在发送请求之前,用回调函数对请求内容和参数做处理,如果没问题则请求正常发送,如果有问题,请求取消

响应拦截器可以在处理结果之前处理,做一个提醒或者记录,或者对数据接口做一些格式化的处理,有问题交由我们自己的回调函数处理,在响应拦截器里做处理

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <script>
//内部还是promise实现的
      // 设置请求拦截器
      axios.interceptors.request.use(
        function (config) {
          console.log('请求拦截器 成功')
          return config
        },
        function (error) {
          console.log('请求拦截器 失败')
          return Promise.reject(error)
        }
      )
 
      // 设置相应拦截器
      axios.interceptors.response.use(
        function (response) {
          console.log('响应拦截器成功')
          return response
        },
        function (error) {
          console.log('响应拦截器 失败')
          return Promise.reject(error)
        }
      )
      //发送请求
      axios({
        method:'GET',
        url:'https://localhost:3000/posts'
      }).then(response=>{
        console.log(response)
      }).catch(reason=>{
        console.log('自定义失败回调')
      })
    </script>
  </body>
</html>

请求拦截器是后进入的先执行,响应拦截器是先进入先执行

在请求拦截器中我们可以修改config的配置:

   axios.interceptors.request.use(
        function (config) {
          console.log('请求拦截器 成功2号 ')
            config.params={a:100}
          return config
        },

返回的数据


http://www.kler.cn/a/574463.html

相关文章:

  • C/C++获取结构体成员的偏移量
  • unsloth-llama3-8b.py 中文备注版
  • 使用 Arduino 的 WiFi 控制机器人
  • 二、双指针——6. 三数之和
  • Python函数定义详细教程:参数类型详解,报错UnboundLocalError怎么解决。
  • 贪心算法一
  • aws(学习笔记第三十一课) aws cdk深入学习(batch-arm64-instance-type)
  • Java多线程与高并发专题——为什么 Map 桶中超过 8 个才转为红黑树?
  • PPT 小黑第20套
  • java8中young gc的垃圾回收器选型,您了解嘛
  • AI面板识别 - 华为OD统一考试(java)
  • 风控模型算法面试题集结
  • 面试基础--Spring Boot启动流程及源码实现
  • IDEA 2024.1.7 Java EE 无框架配置servlet
  • osg官方例子
  • React基础之插值
  • 蓝桥杯 Excel地址
  • 深入剖析 Kubernetes 弹性伸缩:HPA 与 Metrics Server
  • FPGA-按键消抖
  • 青训营:简易分布式爬虫