What is Node request.delete()?

Let’s learn how to make a DELETE request to an API using the Node in-built module request to delete a resource. We can do this using the request.delete() method.

request.delete(URL, Callack());

Parameters

  • URL : The first parameter is the URL of the API where we are making the DELETE request.

  • Callback(): This is a function which will run after the completion or failure of the DELETE method.

Example

var request = require('request');
request.delete(
//First parameter = API to make post request
'https://reqres.in/api/users/2',
//Second parameter = Callack function
function (error, response, body) {
if (!error && response.statusCode == 204) {
console.log(body);
console.log(response.statusCode);
}
}
);

Code explanation

  • On line 1, we import the request module and create an instance.

  • On line 3, we use the request.delete() method.

  • On line 5, we have the URL (API), which is the first parameter of the request.delete() method. This is the server or site that we are requesting.

  • On line 8, we have the callback function, which will execute after the DELETE method is completed. If the DELETE request is successful, then DELETE will return with a response (only the statusCode) and body. If the request fails, then it will return an error.

  • On line 9, we use the if condition to check if our DELETE request is successful or not.

  • On line 10, after checking the if condition, this line will execute. This means that we got no error while making the DELETE request, and we have successfully made a DELETE request.

Click the “Run” button and check the result. We have completed the task to make a DELETE request. The output that we get is empty because delete does not return anything except statusCode after deleting. We can see that the response.statusCode is 204, which implies it is deleted.

Free Resources