axios基礎入門教程

一、axios 簡介

axios 是一個基于 Promise 的 HTTP 客戶端,可用于瀏覽器和 Node.js 環境,支持以下特性:

發送 HTTP 請求(GET/POST/PUT/DELETE 等)

攔截請求和響應

自動轉換 JSON 數據

取消請求

并發請求處理

二、安裝

1. 使用 npm/yarn

npm install axios# 或yarn?add?axios

2. 瀏覽器直接引入

<script?src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

三、基本用法

1. 發送 GET 請求

axios.get('https://api.example.com/data')? .then(response?=>?{? ??console.log(response.data);?// 響應數據? })? .catch(error?=>?{? ??console.error('請求失敗:', error);? });

2. 發送 POST 請求???????

axios.post('https://api.example.com/data', {? ??name:?'John',? ??age:?30? })? .then(response?=>?{? ??console.log(response.data);? });

3. 使用 async/await???????

async?function?fetchData() {??try?{? ??const?response =?await?axios.get('https://api.example.com/data');? ??console.log(response.data);? }?catch?(error) {? ??console.error(error);? }}

四、請求配置

1. 全局默認配置???????

axios.defaults.baseURL?=?'https://api.example.com';axios.defaults.headers.common['Authorization'] =?'Bearer token123';axios.defaults.timeout?=?5000;?// 超時時間

2. 單個請求配置???????

axios.get('/data', {??params: { id:?1?},?// 查詢參數? headers: {?'X-Custom-Header':?'value'?}});

五、響應結構

響應對象包含以下字段:???????

{??data: {}, ? ? ??// 服務器返回的數據? status:?200, ? ?// HTTP 狀態碼? statusText:?'OK',? headers: {}, ? ??// 響應頭? config: {}, ? ? ?// 請求配置? request: {} ? ? ?// 原始的 XMLHttpRequest 對象(瀏覽器)}

六、錯誤處理

1. 通用錯誤捕獲???????

axios.get('/data')? .catch(error?=> {? ??if?(error.response) {? ? ??// 服務器返回了非 2xx 狀態碼? ? ? console.log(error.response.status);? ? ? console.log(error.response.data);? ? }?else?if?(error.request) {? ? ??// 請求已發送但無響應? ? ? console.log('No response received');? ? }?else?{? ? ??// 請求配置錯誤? ? ? console.log('Error:',?error.message);? ? }? });

2. 全局錯誤攔截???????

axios.interceptors.response.use(??response?=>?response,??error?=>?{? ??// 統一處理錯誤? ??return?Promise.reject(error);? });

七、高級功能

1. 并發請求???????

const?request1 = axios.get('/data1');const?request2 = axios.get('/data2');axios.all([request1, request2])? .then(axios.spread((res1, res2) => {? ? console.log(res1.data, res2.data);? }));

2. 取消請求???????

const?source = axios.CancelToken.source();axios.get('/data', {??cancelToken: source.token}).catch(thrown?=>?{??if?(axios.isCancel(thrown)) {? ??console.log('請求被取消:', thrown.message);? }});// 取消請求source.cancel('用戶取消操作');

3. 請求攔截器???????

axios.interceptors.request.use(??config?=>?{? ??// 在發送請求前做些什么(如添加 token)? ? config.headers.Authorization?=?'Bearer token';? ??return?config;? },??error?=>?{? ??return?Promise.reject(error);? });

八、常見場景示例

1. 上傳文件???????

const?formData?=?new?FormData();formData.append('file', fileInput.files[0]);axios.post('/upload', formData, {??headers: {?'Content-Type':?'multipart/form-data'?}});

2. 下載文件???????

axios.get('/download', {?responseType:?'blob'?})? .then(response?=>?{? ??const?url =?window.URL.createObjectURL(new?Blob([response.data]));? ??const?link =?document.createElement('a');? ? link.href?= url;? ? link.setAttribute('download',?'file.pdf');? ??document.body.appendChild(link);? ? link.click();? });

九、最佳實踐

封裝 axios:創建 api.js 統一管理接口

環境區分:通過 .env 文件配置不同環境的 baseURL

安全防護:結合 CSRF Token 或?JWT?進行身份驗證

性能優化:合理設置超時時間,使用緩存策略

示例:

以下是使用 Axios 和 Spring Boot 實現前后端分離的登錄功能的步驟詳解:

1. 后端實現(Spring Boot)

1.1 添加依賴

在 pom.xml 中添加必要依賴:???????

<!-- Spring Web --><dependency>? ??<groupId>org.springframework.boot</groupId>? ??<artifactId>spring-boot-starter-web</artifactId></dependency><!-- 數據庫(以 JPA + H2 為例) --><dependency>? ??<groupId>org.springframework.boot</groupId>? ??<artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency>? ??<groupId>com.h2database</groupId>? ??<artifactId>h2</artifactId>? ??<scope>runtime</scope></dependency><!-- 密碼加密 --><dependency>? ??<groupId>org.springframework.security</groupId>? ??<artifactId>spring-security-crypto</artifactId></dependency>

1.2 配置數據庫和加密

在 application.properties 中配置:???????

spring.datasource.url=jdbc:h2:mem:testdbspring.datasource.driverClassName=org.h2.Driverspring.h2.console.enabled=truespring.jpa.hibernate.ddl-auto=update

1.3 創建用戶實體類???????

@Entitypublic?class?User?{? ??@Id? ??@GeneratedValue(strategy = GenerationType.IDENTITY)? ??private?Long?id;? ??@Column(unique = true)? ??private?String username;? ??private?String password;? ??// Getters and Setters}

1.4 創建 Repository???????

public?interface?UserRepository?extends?JpaRepository<User,?Long> {? ??User?findByUsername(String username);}

1.5 創建 Service 層???????

@Servicepublic?class?AuthService?{? ??@Autowired? ??private?UserRepository?userRepository;? ??@Autowired? ??private?BCryptPasswordEncoder?passwordEncoder;? ??public?boolean?authenticate(String?username,?String?password) {? ? ? ??User?user = userRepository.findByUsername(username);? ? ? ??return?user !=?null?&& passwordEncoder.matches(password, user.getPassword());? ? }}

1.6 創建 Controller???????

@RestController@RequestMapping("/api/auth")@CrossOrigin(origins =?"http://localhost:3000")?// 允許前端跨域請求public?class?AuthController?{? ??@Autowired? ??private?AuthService authService;? ??@PostMapping("/login")? ??public?ResponseEntity<?> login(@RequestBody?LoginRequest loginRequest) {? ? ? ? boolean isValid = authService.authenticate(? ? ? ? ? ? loginRequest.getUsername(),? ? ? ? ? ? loginRequest.getPassword()? ? ? ? );? ? ? ??if?(isValid) {? ? ? ? ? ??return?ResponseEntity.ok().body("登錄成功");? ? ? ? }?else?{? ? ? ? ? ??return?ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用戶名或密碼錯誤");? ? ? ? }? ? }}// 登錄請求DTOpublic?class?LoginRequest?{? ??private?String username;? ??private?String password;? ??// Getters and Setters}

2. 前端實現(使用 Axios)

2.1 安裝 Axios

npm?install axios

2.2 登錄組件示例(React)???????

import?React, { useState }?from?'react';import?axios?from?'axios';const?LoginForm?= () => {? ??const?[username, setUsername] =?useState('');? ??const?[password, setPassword] =?useState('');? ??const?[error, setError] =?useState('');? ??const?handleSubmit?=?async?(e) => {? ? ? ? e.preventDefault();? ? ? ??try?{? ? ? ? ? ??const?response =?await?axios.post(? ? ? ? ? ? ? ??'http://localhost:8080/api/auth/login',? ? ? ? ? ? ? ? { username, password },? ? ? ? ? ? ? ? {?headers: {?'Content-Type':?'application/json'?} }? ? ? ? ? ? );? ? ? ? ? ??if?(response.status?===?200) {? ? ? ? ? ? ? ??alert('登錄成功');? ? ? ? ? ? ? ??// 跳轉到主頁或處理登錄狀態? ? ? ? ? ? }? ? ? ? }?catch?(err) {? ? ? ? ? ??if?(err.response?&& err.response.status?===?401) {? ? ? ? ? ? ? ??setError('用戶名或密碼錯誤');? ? ? ? ? ? }?else?{? ? ? ? ? ? ? ??setError('登錄失敗,請重試');? ? ? ? ? ? }? ? ? ? }? ? };? ??return?(? ? ? ??<form?onSubmit={handleSubmit}>? ? ? ? ? ??<input? ? ? ? ? ? ? ??type="text"? ? ? ? ? ? ? ??value={username}? ? ? ? ? ? ? ??onChange={(e)?=> setUsername(e.target.value)}? ? ? ? ? ? ? ? placeholder="用戶名"? ? ? ? ? ? />? ? ? ? ? ??<input? ? ? ? ? ? ? ??type="password"? ? ? ? ? ? ? ??value={password}? ? ? ? ? ? ? ??onChange={(e)?=> setPassword(e.target.value)}? ? ? ? ? ? ? ? placeholder="密碼"? ? ? ? ? ? />? ? ? ? ? ? {error &&?<div?className="error">{error}</div>}? ? ? ? ? ??<button?type="submit">登錄</button>? ? ? ??</form>? ? );};export?default?LoginForm;

3. 測試流程

啟動 Spring Boot 應用:

mvn?spring-boot:run

啟動前端應用:

npm?start

在登錄頁面輸入用戶名和密碼,驗證是否返回正確響應。

?

?

?

?

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/899654.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/899654.shtml
英文地址,請注明出處:http://en.pswp.cn/news/899654.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

短視頻團隊架構工作流程---2025.3.30 李劭卓

短視頻團隊架構&工作流程—2025.3.30 李劭卓 文章目錄 短視頻團隊架構&工作流程---2025.3.30 李劭卓1 工作職責1.1 編劇&#xff1a;1.2 主編&#xff1a;1.3 總編&#xff1a;1.4 導演&#xff1a;1.5 攝影&#xff1a;1.6 演員&#xff1a;1.7 后期&#xff1a;1.8 美…

MySQL 高效 SQL 使用技巧詳解

MySQL 高效 SQL 使用 技巧詳解 一、為什么需要優化 SQL&#xff1f; 性能瓶頸&#xff1a;慢查詢導致數據庫負載升高&#xff0c;響應時間延長。資源浪費&#xff1a;低效 SQL 可能占用大量 CPU、內存和磁盤 I/O。 目標&#xff1a;通過優化 SQL 將查詢性能提升 10 倍以上&am…

AI基礎03-視頻數據采集

上篇文章我們學習了圖片的數據采集&#xff0c;今天主要了解一下視頻數據采集的方法。視頻是由一系列圖像構成的&#xff0c;其中每一張圖片就是一幀。視頻數據采集方法通常有自動圖像采集和基于處理器的圖像采集兩種。我們學習一下如何利用python 工具和筆記本計算機攝像頭進行…

Scala 數組

Scala 數組 引言 Scala 作為一門多范式編程語言&#xff0c;融合了面向對象和函數式編程的特點。數組是編程語言中非常基礎和常見的數據結構&#xff0c;在 Scala 中也不例外。本文將詳細介紹 Scala 中的數組&#xff0c;包括其定義、操作以及在實際開發中的應用。 Scala 數…

Text-to-SQL將自然語言轉換為數據庫查詢語句

有關Text-To-SQL方法&#xff0c;可以查閱我的另一篇文章&#xff0c;Text-to-SQL方法研究 直接與數據庫對話-text2sql Text2sql就是把文本轉換為sql語言&#xff0c;這段時間公司有這方面的需求&#xff0c;調研了一下市面上text2sql的方法&#xff0c;比如阿里的Chat2DB,麻…

golang 的strconv包常用方法

目錄 1. 字符串與整數的轉換 2. 字符串與浮點數的轉換 3. 布爾值的轉換 4. 字符串的轉義 5. 補充&#xff1a;rune 類型的使用 方法功能詳解 代碼示例&#xff1a; 1. 字符串與整數的轉換 方法名稱功能描述示例Atoi將字符串轉換為十進制整數。strconv.Atoi("123&q…

MATLAB詳細圖文安裝教程(附安裝包)

前言 MATLAB&#xff08;Matrix Laboratory&#xff09;是由MathWorks公司開發的一款高性能的編程語言和交互式環境&#xff0c;主要用于數值計算、數據分析和算法開發。內置數學函數和工具箱豐富&#xff0c;開發效率高&#xff0c;特別適合矩陣運算和領域特定問題。接下來就…

ShapeCrawler:.NET開發者的PPTX操控魔法

引言 在當今的軟件開發領域&#xff0c;隨著數據可視化和信息展示需求的不斷增長&#xff0c;處理 PPTX 文件的場景日益頻繁。無論是自動化生成報告、批量制作演示文稿&#xff0c;還是對現有 PPT 進行內容更新與格式調整&#xff0c;開發者都需要高效的工具來完成這些任務。傳…

HTML5貪吃蛇游戲開發經驗分享

HTML5貪吃蛇游戲開發經驗分享 這里寫目錄標題 HTML5貪吃蛇游戲開發經驗分享項目介紹技術棧核心功能實現1. 游戲初始化2. 蛇的移動控制3. 碰撞檢測4. 食物生成 開發心得項目收獲后續優化方向結語 項目介紹 在這個項目中&#xff0c;我使用HTML5 Canvas和原生JavaScript實現了一…

有關pip與conda的介紹

Conda vs. Pip vs. Virtualenv 命令對比 任務Conda 命令Pip 命令Virtualenv 命令安裝包conda install $PACKAGE_NAMEpip install $PACKAGE_NAMEX更新包conda update --name $ENVIRONMENT_NAME $PACKAGE_NAMEpip install --upgrade $PACKAGE_NAMEX更新包管理器conda update con…

【Linux】調試器——gdb使用

目錄 一、預備知識 二、常用指令 三、調試技巧 &#xff08;一&#xff09;監視變量的變化指令 watch &#xff08;二&#xff09;更改指定變量的值 set var 正文 一、預備知識 程序的發布形式有兩種&#xff0c;debug和release模式&#xff0c;Linux gcc/g出來的二進制…

【Ubuntu常用命令】

1.將本地服務器文件或文件夾傳輸到遠程服務器 文件 scp /data/a.txt administrator10.60.51.20:/home/administrator/ 文件夾 scp -r /data/ administrator10.60.51.20:/home/administrator/ 2.從遠程服務器傳輸文件到本地服務器 scp administrator10.60.51.20:/data/a.txt /h…

golang 的time包的常用方法

目錄 time 包方法總結 類型 time.Time 的方法 庫函數 代碼示例&#xff1a; time 包方法總結 類型 time.Time 的方法 方法名描述示例               ?Now()獲取當前時間和日期time.Now()Format()格式化時間為字符串time.Now().Format("2006-01-02 15…

Elasticsearch:使用 Azure AI 文檔智能解析 PDF 文本和表格數據

作者&#xff1a;來自 Elastic James Williams 了解如何使用 Azure AI 文檔智能解析包含文本和表格數據的 PDF 文檔。 Azure AI 文檔智能是一個強大的工具&#xff0c;用于從 PDF 中提取結構化數據。它可以有效地提取文本和表格數據。提取的數據可以索引到 Elastic Cloud Serve…

【ArcGIS操作】ArcGIS 進行空間聚類分析

ArcGIS 是一個強大的地理信息系統&#xff08;GIS&#xff09;軟件&#xff0c;主要用于地理數據的存儲、分析、可視化和制圖 啟動 ArcMap 在 Windows 中&#xff0c;點擊“開始”菜單&#xff0c;找到 ArcGIS文件夾&#xff0c;然后點擊 ArcMap 添加數據 添加數據 - 點擊工具…

RabbitMQ消息相關

MQ的模式&#xff1a; 基本消息模式&#xff1a;一個生產者&#xff0c;一個消費者work模式&#xff1a;一個生產者&#xff0c;多個消費者訂閱模式&#xff1a; fanout廣播模式&#xff1a;在Fanout模式中&#xff0c;一條消息&#xff0c;會被所有訂閱的隊列都消費。 在廣播…

緩存使用紀要

一、本地緩存&#xff1a;Caffeine 1、簡介 Caffeine是一種高性能、高命中率、內存占用低的本地緩存庫&#xff0c;簡單來說它是 Guava Cache 的優化加強版&#xff0c;是當下最流行、最佳&#xff08;最優&#xff09;緩存框架。 Spring5 即將放棄掉 Guava Cache 作為緩存機…

2025年3月29日筆記

問題&#xff1a;創建一個長度為99的整數數組&#xff0c;輸出數組的每個位置數字是幾&#xff1f; 解題思路&#xff1a; 1.因為題中沒有明確要求需要輸入,所以所有類型的答案都需要寫出 解法1&#xff1a; #include<iostream> #include<bits/stdc.h> using n…

hadoop相關面試題以及答案

什么是Hadoop&#xff1f;它的主要組件是什么&#xff1f; Hadoop是一個開源的分布式計算框架&#xff0c;用于處理大規模數據的存儲和計算。其主要組件包括Hadoop Distributed File System&#xff08;HDFS&#xff09;和MapReduce。 解釋HDFS的工作原理。 HDFS采用主從架構&…

微信小程序:數據拼接方法

1. 使用 concat() 方法拼接數組 // 在原有數組基礎上拼接新數組 Page({data: {originalArray: [1, 2, 3]},appendData() {const newData [4, 5, 6];const combinedArray this.data.originalArray.concat(newData);this.setData({originalArray: combinedArray});} }) 2. 使…