Deleting Data

This API is very similar to addUser API where we receive input data through req.body and then based on user ID we delete that user from the database. To keep our program simple we assume we are going to delete user with ID 2.

server.js

var express = require(‘express’);

var app = express();

var fs = require(“fs”);

var id = 2;

app.delete(‘/deleteUser’, function (req, res) {

// First read existing users.

fs.readFile( __dirname + “/” + “users.json”, ‘utf8’, function (err, data) {

data = JSON.parse( data );

delete data[“user” + 2];

console.log( data );

res.end( JSON.stringify(data));

});

})

var server = app.listen(8081, function () {

var host = server.address().address

var port = server.address().port

console.log(“Example app listening at http://%s:%s”, host, port)

})

Now try to access defined API using URL: http://127.0.0.1:8081/deleteUser and HTTP Method : DELETE on local machine using any REST client. This should produce following result −

{“user1”:{“name”:”mahesh”,”password”:”password1″,”profession”:”teacher”,”id”:1},

“user3”:{“name”:”ramesh”,”password”:”password3″,”profession”:”clerk”,”id”:3}}

Get industry recognized certification – Contact us

Menu