【网络】axios基本使用及简单封装

本文详细介绍了 Axios 的使用,包括其作为函数和对象的两种调用方式,参数类型如 params、query 和请求体参数的设置,以及基本的 GET 和 POST 请求的发送。还讲解了如何设置默认配置、创建实例以及取消请求的方法。此外,重点讨论了拦截器的用法,用于在请求前和响应前进行定制化处理。最后,展示了如何对 Axios 进行二次封装,以实现如添加请求进度条等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、介绍

包,能发ajax,返回promise
本质是函数,函数用法,对象用法。

npm i axios -S

二、三种参数

1、params路径参数

属于路径的一部分
axios当中参数只能写在路径中,没有params设置

axios({
  url:'http://sdfsdfdsfsd/8?name="zhangsan"'
// 8是一个参数 一般是id,传给后台
})

2、query参数

//(1)直接写在url后
?q=v& sort=stars
//(2)使用配置项parmas配置
axios({
 url:'',
 params:{
 q:'v',
 sort:'starts'
}
}

3、请求体参数

向后台提交数据用的,post put 请求体中使用
data参数,配置项data当中去配置

axios({
  url:'',
  data:{
        firstName:"Fred",
        lastName:"Flintstone"
    }
}

三、基本使用

1、函数用法

<button class="btn btn-primary" onclick="sendGET()"> 发送GET请求 </button>

// http://127.0.0.1/server?a=100&b=200

<script>
  function sendGET(){
    axios({
      //是配置对象
      //请求的类型
      method: 'GET',
      //URL设置
      url: 'http://127.0.0.1/server', 
      //参数 
      params: {
        //配的是query参数
        a:100,
        b:200
      },
      //设置请求头信息 查询字符串
      headers: {
        c:300,
        d:400
      }
    }).then(response => {
      console.log(response);
    });
}
</script>

2、对象用法

axios.get(url[, config]) //get请求用于列表和信息查询
axios.delete(url[, config]) //删除
axios.post(url[, data[, config]]) //post请求用于信息的添加
axios.put(url[, data[, config]]) //更新操作

  <div class="container">
  <button class="btn btn-warning" onclick="sendPOST()"> 发送POST请求 </button> 
 <script>
    
function sendPOST(){
 axios.post('http://127.0.0.1/server', 'e=500&f=600', {
      params: {a:100,b:200},
      headers: {c:300,d:400}
    }).then(response => {
      console.log(response);
    })
  }
 </script>

3、默认配置

作用:简化代码

axios.defaults.baseURL = 'http://127.0.0.1';
axios.defaults.method = 'GET';
axios.defaults.timeout = 3000;//超时时间

axios({
  url: '/server',
}).then(response => {
  console.log(response);
})

axios({
  method:'POST',
  url: '/json-server',
}).then(response => {
  console.log(response);
})

4、创建实例

创建实例,封装不同的接口请求

//one和two的使用方式一样
  const one = axios.create({
    baseURL : 'http://www.bd.com',
    method: 'GET',
  });

  const two = axios.create({
    baseURL: 'http://www.jd.com',
    method: "POST"
  });

  one({
    url: '/s',
  }).then(response => {
    console.log(response);
  });

  two({
    url: '/home',
  }).then(response => {
    console.log(response);
  })

5、取消请求

<button>点击发送</button>
<button>点击取消</button>
    <script>
    let btns = document.querySelectorAll('button');
  //获取CanelToken函数
  // let CancelToken = axios.CancelToken;
  //1. 声明变量
  let c = null;
  //
  btns[0].onclick = function () {
    axios({
      //请求方法
      method: 'POST',
      //URL
      url: 'http://127.0.0.1/delay-server',
      //取消请求配置
      cancelToken: new axios.CancelToken(function (cancel){
        //2. 赋值
        c = cancel;
      }),
    }).then(response => {
      console.log(response);
    })
  }

  //绑定事件
  btns[1].onclick = function(){
    //3. 运行 c 函数
    c();
  }
</script>

四、拦截器

只做两件事:干预请求头和响应体、添加额外功能

1、请求拦截器

请求发出之前的钩子,对你的请求进行干预
一般情况下,只去处理成功的,因为几乎不会失败。

   // interceptor属性,request也是属性,use方法,参数两个函数,两个函数叫做拦截器
   // 第一个函数是成功的回调,第二个是失败的回调
   axios.interceptors.request.use(function (config) {
     //config 就是配置对象
     config.params.a = 100;
     config.params.b = 200;
     config.headers = {
       auth: 'a1231231231293012o'
     }
     return config;
   },
     function (error) {
       return Promise.reject(error);
   });

   axios.interceptors.request.use(function (config) {
     //要求必须要有 id 参数
     if (config.params && config.params.id) {
       //1. 如果参数 OK 则返回 config
       return config;
     } else {
       //2. 如果参数有误, 则返回失败的Promise对象, 阻止请求的发送
       return Promise.reject('参数缺失');
     }
   }, function (error) {
     return Promise.reject(error);
   });

2、响应拦截器

在响应之前发出的钩子,对你的响应进行干预。

  axios.interceptors.response.use(function (response) {
      return response;
    }, function (error) {
      return Promise.reject(error);
    });

五、 二次封装

// 二次封装axios

//1、引入
import axios from 'axios'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'


//2、用axios创建新的实例 进行二次封装
// 创建实例,封装不同接口请求
const instance = axios.create({
    //配置基础路径和超时限制
    baseURL: '/api', // 配置基础路径
    timeout: 20000
})

//3、请求拦截器和响应
//拦截器只干两件事:修改报文 添加额外功能
//添加进度条功能 npgross -安装js和css
instance.interceptors.request.use((config) => {
    //请求拦截器一般都只是处理成功的
    let userTempId = store.state.user.userTempId
    if(userTempId){
      config.headers.userTempId = userTempId
    }
  
    //每次请求带上用户的登录标识
    let token = store.state.user.userInfo.token
    if(token){
      config.headers.token = token
    }

    //开启进度条
    Nprogress.start()
    return config
    
})

//响应拦截器
instance.interceptors.response.use(
    //成功的回调
    (response) => {
        //直接返回数据(不返回响应报文)

        //关闭进度条
        Nprogress.done()
        return response.data
    },
    //失败的回调
    (error) => {
        //统一处理请求错误,具体请求也可以选择处理和不处理
        Nprogress.done()
        alert('请求失败'+ error.message || '未知错误')
        //中断promise链  返回pending状态
        return new Promise(() => {})

    }
)

export default instance 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值