How do I make an HTTP request in Javascript?
To make an HTTP request in JavaScript, you can use the `XMLHttpRequest` object or the newer `fetch` API. Here's an example of how to use both methods:
Using XMLHttpRequest:
```javascript
var 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();
```
Using fetch API:
```javascript
fetch("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);
});
```
Both methods demonstrate making a GET request to "https://api.example.com/data" and handling the response. In the examples, the response is assumed to be JSON, so it is parsed using `JSON.parse()` or the `.json()` method of the `Response` object.
You can also make other types of requests (e.g., POST, PUT, DELETE) by adjusting the `open()` method parameters and adding request headers or a request body as needed.
Note that the fetch API is newer and more modern, providing a simpler and more powerful way to make HTTP requests, but the XMLHttpRequest method is still supported in all modern browsers.
Comments
Post a Comment