Axios入门篇🐉

236 阅读1分钟

🐉什么是axios?🐉

  • 1.是一个基于promise的网络请求库(第三方库)
  • 2.主要用来处理服务器之间的数据交互

🐉重要特性🐉

  • 从浏览器创建 XMLHttpRequests

  • 从 node.js 创建 http 请求

  • 🐉🐉🐉支持 Promise API

  • 🐉🐉🐉拦截请求和响应

  • 🐉🐉🐉转换请求和响应数据

  • 取消请求

  • 超时处理

  • 查询参数序列化支持嵌套项处理

  • 自动将请求体序列化为:

    • JSON (application/json)
    • Multipart / FormData (multipart/form-data)
    • URL encoded form (application/x-www-form-urlencoded)
  • 将 HTML Form 转换成 JSON 进行请求

  • 🐉🐉🐉自动转换JSON数据

  • 获取浏览器和 node.js 的请求进度,并提供额外的信息(速度、剩余时间)

  • 为 node.js 设置带宽限制

  • 兼容符合规范的 FormData 和 Blob(包括 node.js)

  • 客户端支持防御XSRF

🐉如何使用?🐉

安装🐉

使用npm方式

npm i axios

创建实例🐉

  • 创建axios实例
const axios = axios.create({  
    baseURL: 'https://noapi.com/api/',  
    timeout: 1000,  
    headers: {'Content-Type': 'application/json;charset=UTF-8'}  
});

拦截🐉

  • 在请求和响应被then和catch处理前拦截它们
  • 可以进行一些请求跟响应的处理
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

常用API🐉

GET

  • 用做查询
axios.get('/api/data', { 
    params: { id: 456 } 
}).then(response => { console.log(response.data); 
}).catch(error => { console.error(error); });

POST

  • 用做添加/查询
axios.post('/api/data', { 
    name:"NI" 
}).then(response => { console.log(response.data); 
}).catch(error => { console.error(error); });

PUT

  • 用做修改
axios.put('/api/data/456', { 
    name: "wo" 
}).then(response => { console.log(response.data); 
}).catch(error => { console.error(error); });

DELETE

  • 用做删除
axios.delete('/api/data/456')
.then(response => { console.log(response.data); })
.catch(error => { console.error(error); });