如何防止axios发送空值?

时间:2020-03-31 17:20:39

标签: node.js reactjs mongoose axios

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

我的状态最初设置为null:

update-database

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

this.state = {

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

}

但是,我的问题是,如果我仅更新一些字段(例如,我只想更新客户的姓名),则这些字段的其余部分将作为空值发布到我的后端,并且使用更新后的值填充数据库。 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 }) 现在替换其余字段。

是否可以通过axios仅发布非空值,还是应该在后端的/ updateCustomer路由中进行更改?谢谢:)

2 个答案:

答案 0 :(得分:0)

Axios发送空值,因为如果仅更新某些值,则未提供的其他值都为空。

因此,您应该做的是在后端的/ updateCustomer路由中,您仅更新从axios传入的值,而不是更新整个对象。

答案 1 :(得分:0)

您应该只使用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 ...