学习vue第六天- axios基本使用

277 阅读2分钟

axios

axios 是一个专注于网络请求的库!
前端最流行的ajax请求库
react/vue官方都推荐使用axios发ajax请求

axios特点

  1. 基于xhr + promise的异步ajax请求库
  2. 浏览器端/node端都可以使用
  3. 支持请求/响应拦截
  4. 支持请求取消
  5. 请求/响应数据转换
  6. 批量发送多个请求

axios常用语法

语法解释
axios(config)通用/最本质的发任意类型请求的方
axios(url[, config])可以只指定url发get请求
axios.request(config)等同于axios(config)
axios.get(url[, config])发get请求
axios.post(url[, data, config])发post请求
axios.put(url[, data, config])发put请求
axios.delete(url[, config])发delete请求
axios.defaults.xxx请求的默认全局配置
axios.interceptors.request.use ()添加请求拦截
axios.interceptors.response.use()添加响应拦截器
axios.create([config])创建一个新的axios(它没有下面的功能)
axios.Cancel()用于创建取消请求的错误对象
axios.CancelToken()用于创建取消请求的token对象
axios.isCancel()是否是一个取消请求的错
axios.all(promises)用于批量执行多个异步请
axios.spread()用来指定接收所有成功数据的回调函数的方法

axios 基本使用

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>;
//GET请求
axios({
  //请求类型
  method: "GET",
  //URL
  url: "http://localhost:3000/posts/2",
}).then((response) => {
  console.log(response);
});
axios.get("http://localhost:3000/posts/2")
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });


//POST请求
axios({
  //请求类型
  method: "POST",
  //URL
  url: "http://localhost:3000/posts",
  //设置请求体
  data: {
    title: "今天天气不错, 还挺风和日丽的",
    author: "张三",
  },
}).then((response) => {
  console.log(response);
});
axios.post("http://localhost:3000/posts",{
    title: "今天天气不错, 还挺风和日丽的",
    author: "张三",
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 //PUT请求 
 axios.put("http://localhost:3000/posts/3",{
    title: "今天天气不错, 还挺风和日丽的",
    author: "李四",
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios({
  //请求类型
  method: "PUT",
  //URL
  url: "http://localhost:3000/posts/3",
  //设置请求体
  data: {
    title: "今天天气不错, 还挺风和日丽的",
    author: "李四",
  },
}).then((response) => {
  console.log(response);
});
//delete请求
 axios.delete("http://localhost:3000/posts/3" )
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios({
  //请求类型
  method: "delete",
  //URL
  url: "http://localhost:3000/posts/3",
}).then((response) => {
  console.log(response);
});