There are several ways to make an HTTP request in JavaScript, but some of the most commonly used methods include using the XMLHttpRequest
object or the newer fetch()
API.
Here’s an example of how to use the XMLHttpRequest
object to make a GET request to a specified URL:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('Request failed. Returned status of ' + xhr.status); } }; xhr.send();
In this example, we first create a new instance of the XMLHttpRequest
object, using the new
keyword. Then, we use the open()
method to specify the type of request (GET, POST, etc.) and the URL that we want to send the request to.
We then set an onload
event handler function that will be called when the request has finished loading. Inside this function, we check the status
property of the xhr
object to see if the request was successful (status code of 200) or not. If it was successful, we print the response text to the console. Otherwise, we print an error message.
Finally, we use the send()
method to send the request.
With POST request the open method is different,
var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://example.com'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('Request failed. Returned status of ' + xhr.status); } }; xhr.send(JSON.stringify({ name: 'Tilak', age: 25 }));
in this example, you can see that we added the setRequestHeader method to set the content-type of the request payload to json, you will have to set the content-type accordingly when using different types of data.
You can also make use of the fetch()
API, which is a more modern alternative to the XMLHttpRequest
object. The fetch()
API uses Promises and is generally easier to use and more flexible than XMLHttpRequest
. Here’s an example of how to use fetch()
to make a GET request:
fetch('https://example.com') .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.error(error))
In this example, we call the fetch()
function, passing in the URL that we want to make the request to. The fetch()
function returns a promise that resolves to a Response
object. We can then use the then()
method to extract the response data, in this case the response.text()
returns a promise that resolve to the data
Also Read: How to Fetch Data From API in React and Display in Table
Leave Your Comment