To make an HTTP request in JavaScript, you can use the XMLHttpRequest
object or the more modern fetch
function.
Here is an example of using XMLHttpRequest
to make a GET request to the JSONPlaceholder API to retrieve a list of users:
Copy codefunction getUsers() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.onload = function() {
if (xhr.status === 200) {
const users = JSON.parse(xhr.responseText);
console.log(users);
}
};
xhr.send();
}
Here is an example of using fetch
to make the same GET request:
Copy codeasync function getUsers() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const users = await response.json();
console.log(users);
}
Both examples will log the array of user objects to the console.
Note that the fetch
function is asynchronous, so you need to use the await
keyword to wait for the response before processing the data. This means the fetch
function should be called inside an async
function.
You can also use fetch
to make POST, PUT, and DELETE requests by passing a second argument to the function with an options object that includes the request method and any other relevant options, such as the request body.
Copy codeconst options = {
method: 'POST',
body: JSON.stringify({
name: 'John',
email: 'john@example.com'
}),
headers: {
'Content-Type': 'application/json'
}
};
const response = await fetch('https://jsonplaceholder.typicode.com/users', options);
Leave a Reply