Difference between PUT and DELETE request in Vanilla JavaScript
Last Updated :
02 Sep, 2021
PUT and DELETE are the two different types of HTTP request methods. HTTP protocol supports many methods to transfer data from the server or do any operation on the server. The HTTP protocol supports the following methods, e.g. GET, POST, PUT, DELETE, PATCH, COPY, HEAD, OPTIONS, etc. Before we dive into the main difference between PUT and DELETE request methods, let us look into HTTP methods.
What is PUT request method?
It is used when the client is sending a replacement document or uploading a new document to the Web server under the request URL.
What is DELETE request method?
It is used when the client is trying to delete a document from the web server, identified by the request URL.
Example: Let us look into an example of PUT request method.
Javascript
function easyHTTP() {
this .http = new XMLHttpRequest();
}
easyHTTP.prototype.put = function (url, data, callback) {
this .http.open( 'PUT' , url, true );
this .http.setRequestHeader(
'Content-type' , 'application/json' );
let self = this ;
this .http.onload = function () {
callback( null , self.http.responseText);
}
this .http.send(JSON.stringify(data));
}
const http = new easyHTTP;
const data = {
title: ‘Custom Putt’,
body: ‘This is a custom put’
};
http.put(
data, function (err, post) {
if (err) {
console.log(err);
}
else {
console.log(post);
}
});
|
Example: The following code demonstrates the DELETE request method.
Javascript
function easyHTTP() {
this .http = new XMLHttpRequest();
}
easyHTTP.prototype. delete = function (url, callback) {
this .http.open( 'DELETE' , url, true );
let self = this ;
this .http.onload = function () {
if (self.http.status === 200) {
callback( null , 'Post Deleted' );
} else {
callback( 'Error: ' + self.http.status);
}
}
this .http.send();
}
const http = new easyHTTP;
http. delete (
function (err, response) {
if (err) {
console.log(err);
} else {
console.log(response);
}
});
|
Difference between PUT and DELETE:
PUT Request |
DELETE Request |
It is used to Create or Modify a resource. |
It is used to delete a resource identified by a URL. |
It is idempotent. |
It is also idempotent. |
On successful resource creation, HTTP success code 201(Created). |
On successful deletion of record, we can see 200 (OK) or 204 (No Content). |
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...