api - 如何在 Axios 发布请求中为布尔值设置 formData
问题描述
我正在尝试使用 axios 向我的后端发送一个发布请求,但由于某种原因我无法发送布尔值“isActive”。有没有办法做到这一点?
async submit() {
const isValid = await this.$validator.validateAll()
if (isValid && !this.submitting) {
let formData = new FormData();
formData.set("city", this.formData.city)
formData.set("state", this.formData.state)
formData.set("county", this.formData.county)
formData.set("isActive", true) // <- NOT ACCEPTING THIS VALUE
axios.post("/api/v1/team/createTeam", formData, {
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.status === 200) {
this.submitting = true
this.cancelModal()
} else {
console.log(res.data.code);
}
})
.catch(function (err) {
console.log(err);
})
}
}
解决方案
FormData
只能包含字符串值。设置布尔值true
将导致"true"
值。后端必须将该字符串转换为布尔值。
此外,您的标头不应application/json
(用于 JSON 有效负载)。如果FormData
作为有效载荷发送,标头应该是multipart/form-data
:
axios.post("/api/v1/team/createTeam", formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
如果您的后端实际上需要 JSON,那么您不能发送FormData
. 改用 JavaScript 对象(它接受布尔值):
const payload = {
city: this.formData.city,
state: this.formData.state,
county: this.formData.county,
isActive: true,
}
axios.post("/api/v1/team/createTeam", payload, {
headers: {
'Content-Type': 'application/json'
}
})
推荐阅读
- javascript - 从 useRef() 获取输入值时获取 useState 是滞后的
- php - PHP-FPM 与 PHP 中的不同语言环境
- python - 为什么在子级上使用打印时调用父类的__str__函数
- scala - 使用 Scala Spark 在不同组中计算复杂统计数据的困难
- java - 使用 spring boot / thymyleaf 重定向到 HTML 页面
- go - 是自定义命名类型的转换函数还是语言构造
- android - 启动阻塞 GC Alloc / 等待阻塞 GC Alloc
- reactjs - React 功能组件,如何通过 onChange 事件动态地将属性传递给输入元素
- android - 将 Recycler View 边缘效果剪辑到 Recycler View Background Drawable
- javascript - 如何从 Prisma 1 迁移到 Prisma 2