Axios

ops/2024/9/24 7:34:48/

文章目录

  • 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/ops/14404.html

相关文章

libtorrent - 安装小记

文章目录 官方文档:libtorrent python binding http://libtorrent.org/python_binding.html 1、下载代码 建议使用: git clone --recurse-submodules https://github.com/arvidn/libtorrent.git如果在 github web 界面下载代码,build 的时候…

基于STM32和阿里云的智能台灯(STM32+ESP8266+MQTT+阿里云+语音模块)

一、主要完成功能 1、冷光模式和暖光模式两种灯光 主要支持冷光和暖光模式两种,可以通过语音模块或手机app远程切换冷暖光 2、自动模式和手动模式 主要支持手动模式和自动两种模式(app或语音助手切换) (1)自动模式:根据环境光照…

Scipy库中FIR滤波器的应用

在上一篇文章《Scipy库中IIR滤波器的应用》中,我们阐述了利用Scipy库进行IIR滤波器设计的一些基本做法。在这篇文章中我们将进一步总结Scipy库在FIR滤波器设计中1的应用。 1. FIR滤波器基本概念   在上篇文章中,我们在给出线性滤波器的差分方程喝系统…

【SAP ME 26】SAP ME创建开发组件(DC)mobile

目录 1、说明 2、创建开发组件(DC) 3、相关性 4、公共部分 5、构建

MAC 安装miniconda

Conda Conda是一个开源跨平台语言无关的包管理与环境管理系统。由“连续统分析”基于BSD许可证发布。 Conda允许用户方便地安装不同版本的二进制软件包与该计算平台需要的所有库。还允许用户在不同版本的包之间切换、从一个软件仓库下载包并安装。 Conda是用Python语言开发&am…

[Java EE] 多线程(三):线程安全问题(上)

1. 线程安全 1.1 线程安全的概念 如果多线程环境下代码运行的结果不符合我们的预期,则我们说存在线程安全问题,即程序存在bug,反之,不存在线程安全问题. 1.2 线程不安全的原因 我们下面举出一个线程不安全的例子:我们想要在两个线程中对count进行操作 public class Demo9 …

缓存神器-JetCache

序言 今天和大家聊聊阿里的一款缓存神器 JetCache。 一、缓存在开发实践中的问题 1.1 缓存方案的可扩展性问题 谈及缓存,其实有许多方案可供选择。例如:Guava Cache、Caffine、Encache、Redis 等。 这些缓存技术都能满足我们的需求,但现…

基于python+django+mysql农业生产可视化系统

博主介绍: 大家好,本人精通Java、Python、C#、C、C编程语言,同时也熟练掌握微信小程序、Php和Android等技术,能够为大家提供全方位的技术支持和交流。 我有丰富的成品Java、Python、C#毕设项目经验,能够为学生提供各类…