htmlmysqlnode.jsangularangular-fullstack

How to send a number to node.js from Angular


I am working on a full stack development using Angular, Node and mySQL. I have to send an index number of a list that the user clicks on an HTML, to a node.js where then, I will have to delete that index row from mySQL. However, I am getting an unusual error. This is my code:

HTML

<tbody *ngFor = "let db of dbData" >
          <tr>
            <td>{{+db.idoffice + +1}}</td>
            <td>{{db.ProjectName}}</td>
            <td>{{db.FiscalYear}}</td>
            <td>{{db.TaskDescription}}</td>
            <td>{{db.ConcernedDepartment}}</td>
            <td>{{db.ActivityType}}</td>
            <td>{{db.Quarter}}</td>
            <td>{{db.kra}}</td>
            <td>{{db.CurrentStatus}}</td>
            <td>{{db.ResourceName}}</td>
            <td>{{db.Notes}}</td>
            <td><button class = "btn btn-success nc-icon nc-refresh-69" name="button"></button></td>
            <td><button class = "btn btn-danger nc-icon nc-simple-delete" name="button" (click) = 
            "onDeletePosts(db.idoffice)"></button></td>
          </tr>
        </tbody>

Angular

private onDeletePosts(delData)
    {
      this.http.delete('http://localhost:3000/del', delData)
      .subscribe(responseData => {
        console.log(responseData);
      });
    }

Node.js

router.delete("/del", (req, res) => {
var del = req.body.delData;
console.log(del);

mysqlConnection.query("DELETE FROM office WHERE idOffice == ?", del , (err, results) => {
  if(!err)
  {
    res.send(results);
  }
  else
  {
    console.log("Error occured while deleting" + err.message);
  }
})
})

This is the error that I am getting:

undefined       //somehow the data from angular to node isn't being received                                                                                                               
Error occured while deletingER_PARSE_ERROR: You have an error in your SQL syntax; check the manual 
that corresponds to your MySQL server version for the right syntax to use near '== ?' at line 1 

Solution

  • Angular HttpClient's delete method does not take a body in it's argument. Instead you could send the ID as an URL query parameter.

    Angular

    import { HttpClient, HttpParams } from '@angular/common/http';
    
    private onDeletePosts (delData: any) {
      const params = new HttpParams().set('id', delData);
      this.http.delete('http://localhost:3000/del', { params }).subscribe({
        next: responseData => { console.log(responseData); },
        error: error => { console.log(error); }
      });
    }
    

    Node.js

    router.delete("/del", (req, res) => {
      var id = req.query.id;
      console.log(id);
    
      mysqlConnection.query("DELETE FROM office WHERE idOffice == ?", id, (err, results) => {
        if (!err) {
          res.send(results);
        } else {
          console.log("Error occured while deleting" + err.message);
        }
      })
    })