一、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:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update
1.3 創建用戶實體類???????
@Entity
public?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 層???????
@Service
public?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("用戶名或密碼錯誤");
? ? ? ? }
? ? }
}
// 登錄請求DTO
public?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
在登錄頁面輸入用戶名和密碼,驗證是否返回正確響應。
?
?
?
?
?