Javascript, you can make an HTTP request using the built-in fetch()
method or the XMLHttpRequest
object. Here’s how to use each method:
The fetch()
method is a modern way to make HTTP requests in Javascript. It returns a Promise that resolves with the response from the server. Here’s an example of how to use it:
fetch(‘https://example.com/api/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 the URL 'https://example.com/api/data'
. The response from the server is returned as a Promise. We then parse the response body as JSON and log it to the console.
The XMLHttpRequest
object is an older way to make HTTP requests in Javascript. It has been replaced by the fetch()
method in most cases, but it’s still supported by most browsers. Here’s an example of how to use it:
const xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://example.com/api/data’);
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error(‘Request failed. Returned status of ‘ + xhr.status);
}
};
xhr.send();
In this example, we create a new XMLHttpRequest
object and use the open()
method to specify the HTTP method (GET) and URL. We then set the onload
event handler to handle the response from the server. If the status code is 200 (OK), we parse the response body as JSON and log it to the console. If the status code is not 200, we log an error message to the console. Finally, we call the send()
method to send the request to the server.
Upcoming Request Movies
Leave a Message