反应中的删除请求不会删除

时间:2019-07-05 10:52:53

标签: node.js reactjs

所以我试图在前端UI上的React中做一个delete方法,我收到200 ok请求,但是我可能做错了,所以这是我的前端和后端代码以及Ui的屏幕截图

enter image description here

 front end




import React, {Component} from 'react';
    import './App.css';
    import axios from 'axios';
    export default class TableRow extends Component {
    constructor(props) {
      super(props);
     this.deletestudent = this.deletestudent.bind(this);
    }
       deletestudent(student_id) {

     axios.post('http://localhost:3200/students/deleteStudent')
     .then(console.log('Student Deleted'))
     .catch(err => console.log(err));
   }
  render(){
    return(
      <tr>
            <td>{this.props.object._id}</td>
            <td>{this.props.object.role_num} </td>
             <td>{this.props.object.first_name}</td>
            <td>{this.props.object.last_name}</td>
            <td><button className = 'btn-btn-danger'>Update</button> </td>
            <td><button onClick={this.deletestudent} className = 'btn-btn-danger' color='blue'> Remove</button></td>
     </tr>
    );
  }
}

后端

second.post('/students/deleteStudent', (req, res) => {

   res.send('delete student'+req.body._id);
    try {
     db.collection('students').deleteOne( { "_id" : ObjectID(req.body._id) } );
  } catch (e) {
   console.log(e);
  }
     res.send('delete student');
  });

当我单击响应时,我得到未定义的删除学生,是否需要更改后端,我知道我需要按ID进行删除,但无法弄清楚

1 个答案:

答案 0 :(得分:0)

这里需要两次更正。

  1. _.id作为student_id传递给deletestudent函数或从道具中使用。
  2. 在您的axios帖子通话中传递student_id

代码

import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
export default class TableRow extends Component {
    constructor(props) {
        super(props);
        this.deletestudent = this.deletestudent.bind(this);
    }
    deletestudent() {
        axios.post('http://localhost:3200/students/deleteStudent', {
            '_id': this.props.object._id
        })
            .then(console.log('Student Deleted'))
            .catch(err => console.log(err));
    }
    render() {
        return (
            <tr>
                <td>{this.props.object._id}</td>
                <td>{this.props.object.role_num} </td>
                <td>{this.props.object.first_name}</td>
                <td>{this.props.object.last_name}</td>
                <td><button className='btn-btn-danger'>Update</button> </td>
                <td><button onClick={this.deletestudent} className='btn-btn-danger' color='blue'> Remove</button></td>
            </tr>
        );
    }
}