Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

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:

1. Using XMLHttpRequest:
javascriptCopy code
// Create a new XMLHttpRequest object var xhr = new XMLHttpRequest (); // Configure the request
xhr. open ( 'GET' , 'https://api.example.com/data' , true ); // Set up a callback function to handle the response
xhr. onload = function () { if (xhr. status === 200 ) { // Request was successful var response =
JSON . parse (xhr. responseText ); console . log (response); } else { // Request failed console . log ( 'Error: ' +
xhr. status ); } }; // Send the request xhr. send ();
2. Using fetch:
javascriptCopy code
fetch ( 'https://api.example.com/data' ) . then ( function ( response ) { if (response. ok ) { // Request was
successful return response. json (); } else { // Request failed throw new Error ( 'Error: ' +
response. status ); } }) . then ( function ( data ) { console . log (data); }) . catch ( function ( error ) {
console . log (error); });

Both methods allow you to make HTTP requests, but the fetch API is newer and
provides a more modern and flexible way of handling requests. However,
XMLHttpRequest is still widely supported in older browsers. You can choose the
method that best fits your requirements.

You might also like