Axios

1 什么是axios

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

2 axios特征

  • 从浏览器创建 XMLHttpRequests

  • 从 node.js 创建 http 请求

  • 支持 promise API

  • 拦截请求和响应

  • 转换请求和响应数据

  • 取消请求

  • 自动转换JSON数据

  • 客户端支持防御[XSRF]

3.Axios 的一些基本 API 和用法

3.1发送 HTTP 请求

axios(config): 发送一个 HTTP 请求,并返回一个 Promise 对象,可以通过传递一个配置对象 config 来定制请求。

axios({
  method: 'get',
  url: 'https://api.example.com/get',
  params: {
    key: 'value'
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

axios.get(url[, config]): 发送一个 GET 请求。

axios.get('https://api.example.com/get', {
  params: {
    key: 'value'
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

axios.post(url[, data[, config]]): 发送一个 POST 请求

axios.post('https://api.example.com/post', {
  key: 'value'
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

axios.put(url[, data[, config]]): 发送一个 PUT 请求。

axios.delete(url[, config]): 发送一个 DELETE 请求。

axios.patch(url[, data[, config]]): 发送一个 PATCH 请求。

3.2 配置项

url: 请求的 URL。

method: HTTP 方法(GET、POST、PUT、DELETE、PATCH 等)。

params: URL 参数。

data: 请求体数据(仅在 POST、PUT、PATCH 等请求中有效)。

headers: 请求头。

timeout: 请求超时时间。

auth: HTTP 基本认证信息。

responseType: 响应的数据类型(例如 jsonblobtext 等)。

3.3 响应处理

Axios 的响应对象具有 data, status, statusText, headers, config, request 等属性。

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data); // 响应数据
    console.log(response.status); // HTTP 状态码
  })
  .catch(error => {
    console.error(error); // 错误处理
  });

3.4 拦截器

Axios 允许你在请求或响应被 thencatch 处理前拦截它们。可以用来转换请求数据、添加公共请求头、处理错误等。

// 请求拦截器
axios.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  return config;
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(response => {
  // 对响应数据做点什么
  return response;
}, error => {
  // 对响应错误做点什么
  return Promise.reject(error);
});

 

4.vue3使用axios发送请求

4.1 安装axios插件
 npm install axios
 4.2 在main.js文件使用axios
 import axios from 'axios'
 const app = createApp(App);
 //使用axios, 并把axios作为app的全局属性
 app.config.globalProperties.$axios=axios;
 app.mount('#app')
4.3  axios发送get请求demo
this.$axios.get("https://autumnfish.cn/cloudsearch?keywords=" + this.query)
 				.then(function(response) {
 					console.log(response)
 					that.musicList = response.data.result.songs;
 				}, function(err) {});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值