主题
传递参数:params vs data
在 Axios 中,根据请求方法的不同,传递参数的方式也有所不同:
params:用于 GET 请求,将参数拼接在 URL 后;data:用于 POST/PUT/DELETE 请求,作为请求体发送。
1. 使用 params(GET 请求)
javascript
import axios from "axios";
axios
.get("https://api.example.com/users", {
params: {
id: 123,
status: "active",
},
})
.then((res) => console.log(res.data))
.catch((err) => console.error(err));输出 URL 实际为:
https://api.example.com/users?id=123&status=active
2. 使用 data(POST/PUT 请求)
javascript
axios
.post("https://api.example.com/users", {
name: "Alice",
age: 25,
})
.then((res) => console.log(res.data))
.catch((err) => console.error(err));POST 请求参数会放在请求体中发送,而不是 URL 上。
3. 对比总结
| 方式 | 请求类型 | 参数位置 | 示例 |
|---|---|---|---|
params | GET | URL 查询字符串 | ?id=123&status=active |
data | POST / PUT / DELETE | 请求体 | { name: 'Alice', age: 25 } |
💡 小提示:选择正确的参数传递方式,可以让接口调用更符合 RESTful 规范,避免请求出错或参数丢失。