# 请求拦截器的作用与用法

URL: https://caijiao.org/axios/interceptors/request
Source: docs/axios/interceptors/request.md
Description: 本章节介绍 Axios 请求拦截器的作用及使用方法，包括在发送请求前统一处理请求头、添加认证信息或日志记录，并通过示例展示如何在前端项目中灵活应用请求拦截器。

Axios 的请求拦截器可以在请求发送之前，对请求配置进行处理，常用于添加认证信息、统一设置 headers、日志记录或参数处理。

## 1. 添加请求拦截器

```javascript
import axios from "axios";

const instance = axios.create({
  baseURL: "https://api.example.com",
  timeout: 7000,
});

instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做处理，例如添加 Token
    const token = localStorage.getItem("auth_token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }

    console.log("请求配置：", config);
    return config;
  },
  (error) => {
    // 请求错误处理
    return Promise.reject(error);
  }
);
```

## 2. 请求拦截器应用场景

- **统一添加 Token**：无需每个请求单独添加认证信息；
- **日志记录**：记录请求参数和 URL 便于调试；
- **动态修改参数**：根据环境或用户信息动态修改请求配置；
- **防止重复请求**：可在拦截器中判断重复请求并取消。

## 3. 使用示例

```javascript
instance
  .get("/users/123")
  .then((res) => console.log("用户数据：", res.data))
  .catch((err) => console.error("请求失败：", err));
```

---

> 💡 小提示：请求拦截器在发送请求前统一处理配置，提高代码可维护性和安全性，尤其适合大型前端项目。
