Axios

server/2024/10/18 8:26:08/

文章目录

  • Axios
    • Axios特性
    • 安装
    • 使用方法
    • Axios 实例
    • 拦截器
    • 取消请求
    • 响应结构
    • 错误处理
    • 在Vue中封装Axios

Axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

文档:https://axios.nodejs.cn/

Axios特性

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防止 CSRF

安装

使用 npm:

$ npm install axios

使用 yarn:

$ yarn add axios

使用方法

发送一个 GET 请求:

javascript">axios.get('/user', {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);}).finally(function () {// always executed});  

Axios 也支持 POST 请求:

javascript">axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});

发送表单数据:

const {data} = await axios.post('https://httpbin.org/post', {firstName: 'Fred',lastName: 'Flintstone',orders: [1, 2, 3],photo: document.querySelector('#fileInput').files}, {headers: {'Content-Type': 'multipart/form-data'}}
)

Axios 实例

我们可以使用自定义配置创建一个新的 axios 实例。

const instance = axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}
});

拦截器

可以在请求或响应被 then 或 catch 处理前拦截它们:

javascript">// Add a request interceptor
axios.interceptors.request.use(function (config) {// Do something before request is sentreturn config;}, function (error) {// Do something with request errorreturn Promise.reject(error);});// Add a response interceptor
axios.interceptors.response.use(function (response) {// Any status code that lie within the range of 2xx cause this function to trigger// Do something with response datareturn response;}, function (error) {// Any status codes that falls outside the range of 2xx cause this function to trigger// Do something with response errorreturn Promise.reject(error);});

取消请求

Axios 允许创建自定义的实例,配置默认的请求行为:
javascript
// Create an instance with the default settings
const instance = axios.create({baseURL: 'https://api.example.com'
});// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;// Send a GET request
instance.get('/user/12345').then(function(response){console.log(response.data);});

响应结构

响应的数据结构包括以下几个重要部分:

javascript">axios.get('/user/12345').then(function(response) {console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});

错误处理

处理请求错误时,Axios 会将错误封装在一个统一的对象中:

javascript">axios.get('/user/12345').catch(function (error) {if (error.response) {// The request was made and the server responded with a status code// that falls out of the range of 2xxconsole.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);} else if (error.request) {// The request was made but no response was receivedconsole.log(error.request);} else {// Something happened in setting up the request that triggered an Errorconsole.log('Error', error.message);}console.log(error.config);});

在Vue中封装Axios

import axios from "axios";
import { ElMessage } from "element-plus";const baseURL = "http://127.0.0.1:8000";
const instance = axios.create({baseURL: baseURL,timeout: 5000,
});instance.interceptors.request.use((config) => {// 添加用户tokenreturn config;},(e) => Promise.reject(e)
);// 添加响应拦截器
instance.interceptors.response.use(function (response) {// 2xx 范围内的状态码都会触发该函数。// 对响应数据做点什么return response;},async function async(error) {// 超出 2xx 范围的状态码都会触发该函数。// 对响应错误做点什么if (error.response.status === 401) {// 可验证用户是否登录ElMessage.error("登录状态失效,请重新登录");}ElMessage.error(error.response.data.detail || error.response.data.error || "服务异常");return Promise.reject(error);}
);export default instance;
export { baseURL };

http://www.ppmy.cn/server/14478.html

相关文章

【C语言】联合体详解

目录 1.联合体的声明 2.联合体的特点 3.相同成员的结构体和联合体对比 4.联合体大小的计算 1.联合体的声明 像结构体一样,联合体也是由一个或者多个成员构成,这些成员可以不同的类型。但是编译器只为最大的成员分配足够的内存空间。 联合体的特点是所…

区分stable diffusion中的通道数与张量维度

区分stable diffusion中的通道数与张量形状 1.通道数:1.1 channel 31.2 channel 4 2.张量形状2.1 3D 张量2.2 4D 张量2.2.1 通常2.2.2 stable diffusion 3.应用3.1 问题3.2 举例3.3 张量可以理解为多维可变数组 前言:通道数与张量形状都在数值3和4之间…

设计模式-状态模式在Java中的使用示例-信用卡业务系统

场景 在软件系统中,有些对象也像水一样具有多种状态,这些状态在某些情况下能够相互转换,而且对象在不同的状态下也将具有不同的行为。 为了更好地对这些具有多种状态的对象进行设计,我们可以使用一种被称之为状态模式的设计模式…

【Python-编程模式】

Python-编程模式 ■ 单例模式■ 工厂模式■■ ■ 单例模式 新建文件 str_tools.py 如下代码。 class StrTools:passstr_tool StrTools()在其他文件使用时导入该变量。 from str_tools_py import str_tool s1 str_tool s2 str_tool print(id(s1)) print(id(s2))■ 工厂模式…

20240330-1-词嵌入模型w2v+tf-idf

Word2Vector 1.什么是词嵌入模型? 把词映射为实数域向量的技术也叫词嵌⼊ 2.介绍一下Word2Vec 谷歌2013年提出的Word2Vec是目前最常用的词嵌入模型之一。Word2Vec实际是一种浅层的神经网络模型,它有两种网络结构,分别是连续词袋&#xff…

Hive 数据倾斜

1.什么是数据倾斜 数据倾斜:数据分布不均匀,造成数据大量的集中到一点,造成数据热点。主要表现为任务进度长时间维持在 99%或者 100%的附近,查看任务监控页面,发现只有少量 reduce 子任务未完成,因为其处理…

MATLAB命令

MATLAB是一个用于数值计算和数据可视化的交互式程序。您可以通过在命令窗口的MATLAB提示符 ‘>>’ 处键入命令来输入命令。 在本节中,我们将提供常用的通用MATLAB命令列表。 用于管理会话的命令 MATLAB提供了用于管理会话的各种命令。下表提供了所有此类命令…

【Linux】NFS网络文件系统搭建

一、服务端配置 #软件包安装 [roothadoop01 ~]# yum install rpcbind nfs-utils.x86_64 -y [roothadoop01 ~]# mkdir /share#配置文件修改 #格式为 共享资源路径 [主机地址] [选项] # [roothadoop01 ~]# vi /etc/exports /share 192.168.10.0/24(rw,sync,no_root_squash) #…