首页 > 解决方案 > 如何在 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);
            })
        }
}

标签: apivue.jsaxios

解决方案


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'
  }
})

推荐阅读