Nodejs rest api delete function

15,444

You can pass an id in your delete route, like below :

Client side :

 $http.delete('/writer/' + id)
        .success(function(data) {
         console.log('Success: ' + data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });

Server side :

   app.delete('/writer/:id', function (req, res) {

    var id = req.params.id;

    //DELETE YOUR RECORD WITH YOUR PARAM.

    return res.status(200);
}

Tell me if I've answered your question.

Share:
15,444
DzouSi
Author by

DzouSi

Updated on July 02, 2022

Comments

  • DzouSi
    DzouSi almost 2 years

    I am writing nodejs rest API. I have problems with my delete function. This my html code:

    <tr ng-repeat="row in displayedCollection">
        <td>{{row.FirstNameAuthor}}</td>
        <td>{{row.LastNameAuthor}}</td>
        <td>
        <button type="button" ng-click="deleteWriter(row)" class="btn btn-sm btn-danger">
        </button>
        </td>
    </tr>
    

    This my core.js code:

    $scope.deleteWriter = function (row) {
        $http.delete('/writer', $scope.row)
              .error(function (data) {
                console.log('Error: ' + data);
              });
        };
    

    This my server.js code:

    app.delete('/writer', function (req, res) {
        var reqBody = '';
    
        req.on("data", function (data) {
            reqBody += data;
            if (reqBody.length > 1e7) {//10MB
                httpMsgs.show404(req, res);
            }
        });
        req.on("end", function () {
            wr.delete(req, res, reqBody);
        });
    })
    

    Then I use function wr.delete to remove record from database.

    exports.delete = function (req, resp, reqBody) { 
    
    try {
        if (!reqBody) throw new Error("Input is nod valid");
        var data = JSON.parse(reqBody);
        if (data) {
            if (!data.idRegisterIssueContract) throw new Error("No such number");
            var sql = "DELETE FROM registerissuecontract ";
            sql += " WHERE idRegisterIssueContract =" + data.idRegisterIssueContract;
            db.executeSQL(sql, function (data, err) {
                if (err) {
                    httpMsgs.show500(req, resp, err);
                }
                else {
                    httpMsgs.send200(req, resp);
                }
    
            });
        }
        else {
            throw new Error("Input is nod valid");
        }
    }
    catch (ex) {
        httpMsgs.show500(req, resp, ex);
    }
    };
    

    But it does not work because reqBody is empty.

    How can I fixed it?