How do I make an HTTP request in Javascript?۔
- Get link
- X
- Other Apps
In JavaScript, you can make an HTTP request using the XMLHttpRequest
object or the newer fetch()
function. Here's an example of how to use each method:
Using XMLHttpRequest:
javascriptvar xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
In the above code, we create a new instance of XMLHttpRequest
using the new XMLHttpRequest()
constructor. Then, we use the open()
method to specify the HTTP method ("GET" in this case) and the URL to which we want to send the request. The third parameter, true
, indicates that the request should be asynchronous.
Next, we define an onreadystatechange
event handler function that will be called when the readyState changes. We check if the readyState is 4 (indicating the operation is complete) and the status is 200 (indicating a successful request). If both conditions are met, we parse the response using JSON.parse()
(assuming the response is in JSON format) and log it to the console.
Finally, we send the request using the send()
method.
Using fetch():
javascriptfetch("https://api.example.com/data")
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Error: " + response.status);
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
With fetch()
, we directly pass the URL as the parameter. It returns a Promise that resolves to the response. We use the then()
method to handle the response. If the response is successful (response.ok
is true
), we call response.json()
to parse the response as JSON. If there's an error, we throw an error with the corresponding status. Finally, we log the data or error to the console using another then()
or catch()
block.
Both methods can be used to make different types of requests (GET, POST, PUT, DELETE, etc.) by modifying the request parameters and headers accordingly.
- Get link
- X
- Other Apps
Comments
Post a Comment