make a http put request in javascript

You can make a HTTP PUT request in JavaScript by using the XMLHttpRequest object. Here's an example:

index.tsx
let xhr = new XMLHttpRequest();
xhr.open("PUT", "https://example.com/api/resource", true);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        console.log("PUT request successful!");
    }
};

let data = JSON.stringify({
    name: "John",
    age: 30
});

xhr.send(data);
399 chars
17 lines

In this example, we create a new XMLHttpRequest object and set the method to PUT and the URL to https://example.com/api/resource. We also set the Content-Type header to application/json.

The onreadystatechange function will be called whenever the state of the request changes. When the readyState is XMLHttpRequest.DONE and the status is 200, we know that the request was successful.

We also create a data object which we serialize into a JSON string using JSON.stringify(). This data will be sent as the body of the request using the send() method.

Note that this is just one way to make a PUT request in JavaScript. There are other libraries such as axios and fetch which provide simpler and more concise syntax.

gistlibby LogSnag