教程 axios tutorial

Axios 请求配置对象详解

Axios 允许在发送请求时传入配置对象,用于控制请求的行为和参数。掌握这些配置可以让开发者更灵活地处理不同接口需求。

1. 基本请求配置

javascript
import axios from "axios";

axios({
  method: "get", // 请求方法
  url: "https://api.example.com/data", // 请求地址
  params: { id: 123 }, // URL 查询参数
  headers: { "X-Custom-Header": "value" }, // 自定义请求头
  timeout: 5000, // 请求超时(毫秒)
})
  .then((response) => console.log(response.data))
  .catch((error) => console.error(error));

2. 主要配置属性

属性 说明
url 请求地址
method 请求方法,如 GET、POST、PUT、DELETE
baseURL 基础 URL,会与 url 拼接
params GET 请求的 URL 参数
data POST/PUT 请求的请求体数据
headers 自定义请求头
timeout 请求超时时间(毫秒)
responseType 响应类型,如 json、blob、text
withCredentials 跨域请求时是否携带凭证

3. 实例演示

javascript
axios({
  method: "post",
  url: "/login",
  baseURL: "https://api.example.com",
  data: { username: "Alice", password: "123456" },
  headers: { "Content-Type": "application/json" },
  timeout: 7000,
})
  .then((res) => console.log("登录成功:", res.data))
  .catch((err) => console.error("请求失败:", err));

💡 小提示:合理使用请求配置对象可以极大提高 Axios 的灵活性,例如设置全局 baseURL、统一请求超时或自定义请求头,为项目开发带来便利。