2024从零开始使用VSCode编程之“axios”

目录

一、axios简介

注意:本教程仅供参考,详细教程请前往官方网站查看起步 | Axios Docs (axios-http.com)

二、axios的安装

三、axios

目录

一、axios简介

注意:本教程仅供参考,详细教程请前往官方网站查看起步 | Axios Docs (axios-http.com)

二、axios的安装

三、axios

1、请求方法(RESTful API风格)

2、请求方法的代码实现(RESTful API风格)

3、一个较为完整的请求结构(演示)

4、axios常见请求配置

5、axios的响应结构

6、拦截器(通常用于登录界面的拦截)

四、axios的简单案例

五、参考文档


本文只为记录并帮助有需要的小伙伴学习使用VScode进行前端开发


注意本教程发布于2024年7月,软件为win1.91,后续版本使用时也可参考

一、axios简介

注意:本教程仅供参考,详细教程请前往官方网站查看起步 | Axios Docs (axios-http.com)

简介:axios是基于AJAX(异步JavaScript和XML)进行构建的,但它对AJAX进行了封装和扩展,使其更易用和功能更强大,axios也主要用于前端和后端的交互当中,主要用于发送HTTP请求和处理响应数据

注意:相较于vue这类框架axios更像是一个工具库,所以axios需要学习的东西就没有vue那么多

二、axios的安装

①新建终端

②输入命令"npm install axios"安装axios

③输出类似以下内容表示安装成功

也可以用命令检查“npm list axios

三、axios

axios在前端开发中主要用于在浏览器中发送请求,简洁的API使得它发送和响应请求变得简单

1、请求方法(RESTful API风格)

①get获取资源,通常用于获取数据,例如获取商品信息

②post创建新资源,通常用于向服务端传送数据,例如上传个人信息

③put更新现有资源,通常用于更新服务器上的现有资源,例如更新用户的个人信息。

④Delete删除资源,通常用于删除数据,例如删除收藏商品 

⑤patch部分更新资源,通常用于对资源进行部分更新,而不是完全替换,例如更改用户名

2、请求方法的代码实现(RESTful API风格)

在前端的axios代码编写中有两种书写格式,

第一种是直接调用(.get):适合简单请求

第二种是通过配置对象实现(method:'get'):适合需要配置很多选项的请求,复杂请求

①get获取资源

直接

axios.get('https://cunminbiao/user', {
  params: {
    Name: '张三'
  }
})
.then(response => {
  console.log('Response Data:', response.data); // 处理响应数据
})
.catch(error => {
  console.error('Error with request:', error); // 处理错误
});

配置对象

axios({
  method: 'get', // 请求方法
  url: 'https://cunminbiao/userlist', // 请求 URL
  params: { // URL 查询参数
    Name: '张三' // 确保参数名称和服务器期望的格式匹配
  }
})
.then(response => {
  console.log('Response Data:', response.data); // 处理响应数据
})
.catch(error => {
  console.error('Error with request:', error); // 处理错误
});

②post创建新资源

直接

axios.post('https://cunminbiao/userlist', {
    firstName: '张',
    lastName: '三'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error posting data:', error);
  });

配置对象

const config = {
  method: 'post',
  url: 'https://cunminbiao/userlist',
  data: {
    firstName: '张',
    lastName: '三'
  },
  headers: { 'Content-Type': 'application/json' }
};

axios(config)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error with request:', error);
  });

③put更新现有资源

直接

axios.put('https://cunminbiao/user', {
    firstName: '张',
    lastName: '三'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error updating data:', error);
  });

配置对象

axios({
  method: 'patch', // 请求方法
  url: 'https://cunminbiao/user', // 请求 URL
  data: { // 请求体中的数据
    firstName: '张'
    lastName: '三'
  },
  headers: { 'Content-Type': 'application/json' } // 请求头
})
.then(response => {
  console.log('Response Data:', response.data); // 处理响应数据
})
.catch(error => {
  console.error('Error with request:', error); // 处理错误
});

④Delete删除资源

直接

axios.delete('https://cunminbiao/user/张三')
  .then(response => {
    console.log('Data deleted');
  })
  .catch(error => {
    console.error('Error deleting data:', error);
  });

配置对象

axios({
  method: 'delete',
  url: 'https://cunminbiao/user/张三'
})
.then(response => {
  console.log('User deleted:', response.data);
})
.catch(error => {
  console.error('Error with request:', error);
});

⑤patch部分更新资源

直接

axios.patch('https://cunminbiao/user/张三', {
    lastName: '四'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error updating data:', error);
  });

配置对象

 axios({
      method: 'patch', // 请求方法
      url: 'https://cunminbiao/user/张三', // 请求 URL
      data: { // 请求体中的数据
        lastName: '四'//改为张四
      },
      headers: { 'Content-Type': 'application/json' } // 请求头
    })
    .then(response => {
      console.log('Response Data:', response.data); // 处理响应数据
    })
    .catch(error => {
      console.error('Error with request:', error); // 处理错误
    });

3、一个较为完整的请求结构(演示)

axios({
  method: 'get', // 请求方法,如 'get', 'post', 'put', 'delete', 'patch'
  url: 'https://cunminbiao/data', // 请求的 URL 地址
  params: { // URL 查询参数,用于 GET 请求
    key1: 'value1',
    key2: 'value2'
  },
  data: { // 请求体数据,用于 POST、PUT、PATCH 请求
    key1: 'value1',
    key2: 'value2'
  },
  headers: { // 请求头部
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your_token_here'
  },
  auth: { // HTTP 基本认证
    username: 'your_username',
    password: 'your_password'
  },
  timeout: 1000, // 请求超时设置,单位为毫秒
  responseType: 'json', // 响应数据类型,如 'json', 'text', 'blob'
  maxRedirects: 5, // 最大重定向次数
  paramsSerializer: function (params) { // 自定义查询参数的序列化函数
    return Qs.stringify(params, { indices: true });
  },
  onDownloadProgress: function (progressEvent) { // 处理下载进度
    console.log('Download progress:', progressEvent);
  },
  onUploadProgress: function (progressEvent) { // 处理上传进度
    console.log('Upload progress:', progressEvent);
  },
  withCredentials: true // 是否发送跨域请求时带上凭证(如 Cookies)
})
.then(response => {
  console.log('Response Data:', response.data); // 处理响应数据
})
.catch(error => {
  console.error('Error with request:', error); // 处理错误
});

4、axios常见请求配置解释(使用介绍)

  • (1):method:指定 HTTP 请求方法,如get/post/put/delete/patch等

  • (2):url:请求的 URL 地址,必须提供

  • (3):params:URL 查询参数,用于 GET 请求。将对象转换为 URL 查询字符串

  • (4):data:请求体数据,用于 POST、PUT、PATCH 请求

  • (5):headers:请求头部,用于设置请求的元信息,如内容类型、认证信息等

  • (6):auth:用于 HTTP 基本认证,包含用户名和密码

  • (7):timeout:请求超时设置,单位为毫秒。超时后请求将被中止

  • (8):responseType:指定响应数据类型,例如JSON/TEXT/BLOB等

  • (9):maxRedirects:指定最大重定向次数,默认值是 5

  • (10):paramsSerializer:用于自定义查询参数的序列化函数

  • (11):paramsSerializer & onDownloadProgress:进度回调,用于处理上传和下载的进度

  • (12):withCredentials:指定是否发送跨域请求时带上凭证(如 Cookies)

5、axios的响应结构

1、then

通常用于处理请求成功时的情景

axios.get('https://api.example.com/data')
  .then(response => {
    console.log('Response Data:', response.data);//打印获取到的数据
  });

2、catch

通常用于处理请求错误的情景

axios.get('https://api.example.com/data')
  .catch(error => {
    console.error('Error with request:', error);// 将错误信息输出到控制台
  });

6、拦截器(在请求或响应被处理前做修改)(参考官网文档)

简单来说,拦截器就是在你访问某个页面时判断你有没有登录,或者某个页面你有没有权限访问

注意:和守卫的目的不一样,守卫主要用控制路由访问,拦截是访问的拦截实现数据预处理和错误处理

①请求拦截器

// 添加请求拦截器
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);
  });

③移除拦截器

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

 ④给axios实例添加拦截器

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

四、axios的简单案例

界面中使用import axios from 'axios';便可将其引入使用

<template>
  <div>
    <h1>发送 GET 请求示例</h1>
    <button @click="sendGetRequest">发送请求</button>
    <ul v-if="users.length">
      <li v-for="user in users" :key="user.id">
        {{ user.name }} - {{ user.email }} - {{ user.role }}
      </li>
    </ul>
    <p v-if="responseMessage">{{ responseMessage }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'GetRequestPage',
  data() {
    return {
      users: [],  // 存储从 Mock Server 获取的用户数据
      responseMessage: ''  // 用于存储请求的响应消息
    };
  },
  methods: {
    sendGetRequest() {
      axios({
        method: 'get',
        url: 'https://cf217b11-dea8-41df-8085-f4c3c21e34ea.mock.pstmn.io/UserList'
      })
      .then(response => {
        // 请求成功,处理响应
        this.users = response.data.data;  // 更新用户数据
        this.responseMessage = '请求成功';
      })
      .catch(error => {
        // 请求失败,输出错误信息
        this.responseMessage = '请求失败: ' + error.message;
        console.error('请求失败:', error);
      });
    }
  }
};
</script>

<style>
/* 可以在这里添加样式 */
</style>

五、参考文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

npc码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值