教程 axios tutorial

设置 baseURL、timeout、headers

Axios 提供了多种方式配置请求的基础 URL、超时时间和自定义请求头,这些配置可以应用于单次请求,也可以应用于全局实例。

1. 配置 baseURL

baseURL 用于设置请求的基础路径,所有相对 URL 都会自动拼接该路径。

javascript
import axios from "axios";

const instance = axios.create({
  baseURL: "https://api.example.com", // 基础 URL
});

instance
  .get("/users") // 实际请求 URL: https://api.example.com/users
  .then((res) => console.log(res.data));

2. 配置 timeout

timeout 用于设置请求超时时间(毫秒),超过该时间未响应将触发错误。

javascript
axios
  .get("https://api.example.com/data", { timeout: 5000 })
  .then((res) => console.log(res.data))
  .catch((err) => console.error("请求超时或出错:", err.message));

3. 配置 headers

可以自定义请求头,用于身份认证、内容类型等场景。

javascript
axios
  .post(
    "/login",
    { username: "Alice", password: "123456" },
    {
      headers: {
        "Content-Type": "application/json",
        "X-Auth-Token": "token123",
      },
    }
  )
  .then((res) => console.log("登录成功:", res.data));

4. 全局配置示例

javascript
axios.defaults.baseURL = "https://api.example.com";
axios.defaults.timeout = 7000;
axios.defaults.headers.common["Authorization"] = "Bearer token123";

💡 小提示:合理使用 baseURL、timeout 和 headers 可以减少重复代码、统一接口请求行为,同时提高请求的可维护性和安全性。