axios用法

Axios是一个基于Promise的HTTP客户端,用于浏览器和node.js环境,可以发送异步HTTP请求到REST端点并处理响应。以下是Axios的基本用法和常用方法:

Axios的基本用法

  1. 安装Axios

    如果你还没有安装Axios,可以通过npm、yarn或其他包管理工具进行安装。例如,使用npm安装Axios的命令如下:

    npm install axios

     

    或者使用yarn:

    yarn add axios

  2. 引入Axios

    在你的项目中,你可以通过importrequire语句来引入Axios。例如,在ES6模块中:

    import axios from 'axios';

     

    或者在CommonJS模块中:

    const axios = require('axios');

  3. 发送请求

    Axios支持多种请求方式,如GET、POST、PUT、DELETE等。以下是一些示例:

    • GET请求

       
          

      axios.get('/user?ID=12345') .then(function (response) { // 处理成功情况         console.log(response);

      }) .catch(function (error) {

      // 处理错误情况

               console.log(error); }) .then(function () {

      // 总是会执行

      });

      // 或者使用

      axios(config) axios({

              method: 'get', url: '/user?ID=12345',

      }) .then(function (response) {

              console.log(response);

      }) .catch(function (error) {

              console.log(error);

      });

       
      • POST请求

         
              

        axios.post('/user', {

                firstName: 'Fred', lastName: 'Flintstone'

        }) .then(function (response) {

                console.log(response);

        }) .catch(function (error) {

                console.log(error);

        });


         
    • PUT请求

axios.put('/user/12345', {

        firstName: 'John', lastName: 'Doe'

}) .then(function (response) {

        console.log(response);

}) .catch(function (error) {

        console.log(error);

});

    • DELETE请求

       
          

      axios.delete('/user/12345') .then(function (response) {

              console.log(response);

      }) .catch(function (error) {

              console.log(error);

      });

Axios的常用配置项

  • url:请求的URL。
  • method:请求方法,如GET、POST、PUT、DELETE等。
  • headers:请求头,可以设置自定义的请求头信息。
  • params:URL查询参数,适用于GET、DELETE请求。
  • data:作为请求主体被发送的数据,适用于POST、PUT、PATCH请求。
  • timeout:请求超时的毫秒数,如果请求耗时超过这个时间,请求将被中断。
  • baseURL:自动加在url前面的基础URL,除非url是一个绝对URL。
  • transformRequest:允许在向服务器发送前修改请求数据,只能用于PUT、POST和PATCH请求。
  • transformResponse:在传递给.then.catch之前,允许修改响应数据。

拦截器

Axios提供了请求拦截器和响应拦截器,允许你在请求或响应被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) { // 对响应错误

  • 24
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值