How do I make an HTTP request in Javascript?
How do I make an HTTP request in Javascript?
In JavaScript, you can make an HTTP request using the XMLHttpRequest
object or the newer fetch
API. Here’s how to use both of these methods:
Using XMLHttpRequest:
// Create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();// Set up a callback for when the request is completed
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// Request was successful, do something with the response
console.log(xhr.responseText);
} else {
// There was an error with the request
console.error(‘Request failed:’, xhr.status);
}
}
};// Open a new GET request to the given URL
xhr.open(‘GET’, ‘http://example.com/api/data’);// Send the request
xhr.send();
Using fetch:
// Make a fetch request
fetch(‘http://example.com/api/data’)
.then(response => {
if (response.ok) {
// Request was successful, parse the response as JSON
return response.json();
} else {
// There was an error with the request
throw new Error(‘Request failed:’, response.status);
}
})
.then(data => {
// Do something with the response data
console.log(data);
})
.catch(error => {
// Handle any errors that occurred during the request
console.error(error);
});
Both of these methods allow you to make HTTP requests and handle the response asynchronously in JavaScript.
You can make an HTTP request in JavaScript using the built-in fetch()
function or by using third-party libraries such as axios
or jQuery
.
Here’s an example of making a GET
request using fetch()
:
fetch('https://example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
fetch(‘https://example.com/data’)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, we’re making a GET
request to https://example.com/data
, parsing the response as JSON, and logging the data to the console. We’re also catching any errors that may occur and logging them to the console as well.
If you want to make a POST
request, you can pass an options object to fetch()
:
fetch('https://example.com/data', {
method: 'POST',
body: JSON.stringify({ name: 'John', age: 30 }),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
fetch(‘https://example.com/data’, {
method: ‘POST’,
body: JSON.stringify({ name: ‘John’, age: 30 }),
headers: {
‘Content-Type’: ‘application/json’
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, we’re making a POST
request to https://example.com/data
with a JSON payload containing the name and age properties. We’re also setting the Content-Type
header to application/json
to indicate that the payload is JSON.
Note that fetch()
returns a Promise, so we’re using then()
and catch()
to handle the response and any errors that may occur.
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://example.com/api/data’);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
else {
console.log(‘Request failed. Returned status of ‘ + xhr.status);
}
};xhr.send();
Using fetch():
fetch(‘https://example.com/api/data’)
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
Both methods allow you to make HTTP requests and retrieve data from a server, but fetch()
is newer and considered more modern and easier to use. It also returns a Promise that resolves to the response object, allowing you to chain multiple promises together.