make a http delete request in javascript

Here are two ways to make an HTTP DELETE request in JavaScript:

Using XMLHttpRequest:

index.tsx
var xhr = new XMLHttpRequest();
xhr.open("DELETE", "http://example.com/api/resource", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
};
xhr.send();
243 chars
9 lines

Using fetch:

index.tsx
fetch('http://example.com/api/resource', {
    method: 'DELETE'
})
.then(response => {
    console.log(response);
})
.catch(error => {
    console.error(error);
});
165 chars
10 lines

Both methods use the HTTP DELETE method to make the request. The first method uses the older XMLHttpRequest object, while the second method uses the newer fetch function that is becoming more popular due to its simplicity and promise-based nature.

gistlibby LogSnag