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 theDELETErequest. -
Callback(): This is a function which will run after the completion or failure of theDELETEmethod.
Example
var request = require('request');request.delete(//First parameter = API to make post request'https://reqres.in/api/users/2',//Second parameter = Callack functionfunction (error, response, body) {if (!error && response.statusCode == 204) {console.log(body);console.log(response.statusCode);}});
Code explanation
-
On line 1, we import the
requestmodule 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 therequest.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
DELETEmethod is completed. If theDELETErequest is successful, thenDELETEwill return with a response (only thestatusCode) and body. If the request fails, then it will return an error. -
On line 9, we use the
ifcondition to check if ourDELETErequest is successful or not. -
On line 10, after checking the
ifcondition, this line will execute. This means that we got no error while making theDELETErequest, and we have successfully made aDELETErequest.
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.