【问题标题】:How to prevent axios from sending null values?如何防止axios发送空值?
【发布时间】:2020-07-12 08:13:29
【问题描述】:

我有一个 axios.post() 请求配置为通过发送当前状态来更新我的 MongoDB 集合中的文档,由文本字段更新。

我的状态最初设置为 null:

this.state = {

  editedCustomer: {
    name: null,
    surname: null,
    alias: null,
    email: null,
    phoneNo: null,
    _id: null
  },

}

这些值直接从文本字段更新,因此每当文本字段接收到输入时,它都会更新状态,然后通过 axios 发送,如下所示:

axios.patch(`${APIURL}/customers/updateCustomer`, {
      'name': this.state.editedCustomer.name,
      'surname': this.state.editedCustomer.surname,
      'alias': this.state.editedCustomer.alias,
      'email': this.state.editedCustomer.email,
      'phoneNo': this.state.editedCustomer.phoneNo,
      '_id': this.state.editedCustomer._id
    })

但是,我的问题是,如果我只更新一些字段(比如我只想更新客户的姓名),其余这些字段将作为 null 发布到我的后端,并且我的数据库将填充更新的值, null 现在替换其余字段。

有没有办法只使用 axios 发布非空值,或者更改是否应该在我后端的 /updateCustomer 路由中。谢谢:)

【问题讨论】:

    标签: node.js reactjs mongoose axios


    【解决方案1】:

    Axios 发送 null 是因为如果您只更新某些值,则未提供的其他值是 null。

    所以你应该做的是在你后端的 /updateCustomer 路由中,你只更新从 axios 传入的值,而不是更新整个对象。

    【讨论】:

      【解决方案2】:

      您应该只使用Object.keys 映射该对象并“过滤”为空的值

      let data = {};//<- Data to send with Axios
      
      Object.keys(this.state.editedCustomer).map((key) => {
        if(editedCustomer[key]) {
          data[key] = editedCustomer[key]
        }
      });
      
      const dataToSend = JSON.stringify(data);
      

      然后您只需使用 Axios/fetch 发布您的 dataToSend...

      【讨论】:

        猜你喜欢
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 2021-08-18
        • 1970-01-01
        • 2019-10-10
        • 1970-01-01
        • 2018-05-04
        • 1970-01-01
        相关资源
        最近更新 更多