make a http put request in typescript

To make a HTTP PUT request in TypeScript, you can use the built-in XMLHttpRequest (XHR) object. Here is an example code snippet:

index.ts
const xhr = new XMLHttpRequest();
xhr.open('PUT', '/api/endpoint', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        // Handle successful response
        console.log(xhr.responseText);
    } else {
        // Handle error response
        console.error(xhr.responseText);
    }
};
xhr.send(JSON.stringify({ data: 'example' }));
442 chars
14 lines

In this code block, we create an instance of the XHR object and use the open() method to specify the request type and endpoint URL. We also set the Content-type header to application/json and define a callback function for the onreadystatechange event.

Inside the callback function, we can check the readyState and status properties of the XHR object to determine if the request was successful. If the request was successful with a 200 status code, we can handle the response by logging the responseText. If there was an error, we can handle the error by logging the responseText.

Finally, we use the send() method to send the JSON data to the server as the request body.

related categories

gistlibby LogSnag