Axios POST 请求
传递 JSON 对象
默认 JSON 对象
axios
.post("/user", {
firstName: "Fred",
lastName: "Flintstone"
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
发起多个并发请求
function getUserAccount() {
return axios.get("/user/12345")
}
function getUserPermissions() {
return axios.get("/user/12345/permissions")
}
const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()])
// OR
Promise.all([getUserAccount(), getUserPermissions()]).then(function ([
acct,
perm
]) {
// ...
})
传递 HTML 表单
JSON 类型
请求头指定了数据的格式为 JSON ("Content-Type": "application/json"
),这种情况下,Axios 会尝试将表单数据转换为 JSON 格式。
const { data } = await axios.post("/user", document.querySelector("#my-form"), {
headers: {
"Content-Type": "application/json"
}
})
form-data 类型
- Multipart (
multipart/form-data
)
上传包含文件或二进制数据的表单,请求头需携带 "Content-Type": "multipart/form-data"
const { data } = await axios.post(
"https://httpbin.org/post",
{
firstName: "Fred",
lastName: "Flintstone",
orders: [1, 2, 3],
photo: document.querySelector("#fileInput").files // 图片文件
},
{
headers: {
"Content-Type": "multipart/form-data"
}
}
)
x-www-form-urlencoded 类型
- URL encoded form (
application/x-www-form-urlencoded
)
键值对通过 URL 编码的形式发送,数据被编码为键值对,通过 & 连接,并在发送请求时放在请求体中。适合发送普通表单数据,但不适用于文件上传等场景。
const { data } = await axios.post(
"https://httpbin.org/post",
{
firstName: "Fred",
lastName: "Flintstone",
orders: [1, 2, 3]
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}
)