如何将数据从React应用发送到本地Rest API

时间:2019-11-27 14:58:54

标签: reactjs rest api axios

我正在使用axios.post方法将数据从React应用发送到api。一切都在本地主机中。 每当我发出发布请求时,数据库都会获得一个创建的新文档,这意味着没有通信问题,但是没有创建数据字段,例如,我的架构具有权重,价格,颜色值,但是创建的新文档仅包含{{ 1}}字段,没有其他内容。

_id

我没有收到任何错误,并且响应也成功

以下是用户输入数据的表单:

  addAnimal(){
    axios.post('http://localhost:5000/animals', this.state.newAnimal).then((response) => {
      console.log(response.data);
    });
  }

我作为数据发送的<ModalBody> <Form.Label for="title">Animal:</Form.Label> <Form.Control type="text" id="title" name="title" value={this.state.newAnimal.title} onChange={(e)=>{ var { newAnimal } = this.state; newAnimal.title = e.target.value; this.setState({newAnimal}); }} /> <Form.Label for="weight">Weight:</Form.Label> <Form.Control type="text" id="weight" value={this.state.newAnimal.weight} onChange={(e)=>{ var { newAnimal } = this.state; newAnimal.weight = e.target.value; this.setState({newAnimal}); }} /> <Form.Label for="color">Color:</Form.Label> <Form.Control type="text" id="color" value={this.state.newAnimal.color} onChange={(e)=>{ var { newAnimal } = this.state; newAnimal.color = e.target.value; this.setState({newAnimal}); }}/> <Form.Label for="price">Price:</Form.Label> <Form.Control type="text" id="price" value={this.state.newAnimal.price} onChange={(e)=>{ var { newAnimal } = this.state; newAnimal.price = e.target.value; this.setState({newAnimal}); }} /> </ModalBody> <ModalFooter> <Button onClick={()=>{this.handleModal()}}>Cancel</Button> <Button onClick={this.addAnimal.bind(this)} >Save</Button> </ModalFooter> </Modal> 对象具有所有字段数据,但是当用文档更新数据库时,该文档只有一个ID,没有其他内容。 这就是我console.log

newAnimal对象的样子
  

{标题:“ ksjdh”,重量:“ 8789”,颜色:“ khjds”,价格:“ 9879”}

但是在数据库中创建的文档为空

0 个答案:

没有答案