Making an HTTP request in JavaScript is a fundamental skill for web developers. In this blog, we'll explore the basics of how to make HTTP requests using the built-in XMLHttpRequest object and the newer fetch() API.
XMLHttpRequest
XMLHttpRequest is a JavaScript object that allows you to send HTTP requests and receive responses. It has been around for a long time and is supported by all major browsers.
Here's an example of how to make an HTTP GET request using XMLHttpRequest:
javascriptCopy code
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed. Status code: ' + xhr.status);
}
};
xhr.send();
In this example, we create a new XMLHttpRequest object, open a GET request to the URL https://jsonplaceholder.typicode.com/todos/1, set the onload event handler to log the response if the status code is 200 (OK), and send the request.
We can also make POST requests and include request headers, like this:
javascriptCopy code
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed. Status code: ' + xhr.status);
}
};
xhr.send(JSON.stringify({ name: 'John', age: 30 }));
In this example, we create a new XMLHttpRequest object, open a POST request to the URL https://example.com/api, set the Content-Type header to application/json, set the onload event handler to log the response if the status code is 200 (OK), and send a JSON payload.
fetch()
The fetch() API is a newer, simpler way to make HTTP requests. It returns a Promise that resolves to the Response object.
Here's an example of how to make an HTTP GET request using fetch():
javascriptCopy code
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Request failed', error));
In this example, we call fetch() with the URL https://jsonplaceholder.typicode.com/todos/1. We then chain two .then() methods: one to parse the response as JSON, and another to log the data. We also include a .catch() method to log any errors that occur.
We can also make POST requests and include request headers, like this:
javascriptCopy code
fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Request failed', error));
In this example, we call fetch() with the URL https://example.com/api and a configuration object that includes the method, headers, and body properties. We then chain two .then() methods: one to parse the response as JSON, and another to log the data. We also include a .catch() method to log any errors that occur.
Comments