0% found this document useful (0 votes)
30 views

How Do I Make An HTTP Request in Javascript

The document discusses two approaches for making HTTP requests in JavaScript - using the built-in XMLHttpRequest object or the newer fetch API. Code examples are provided for making GET requests with both approaches.

Uploaded by

Curry St
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

How Do I Make An HTTP Request in Javascript

The document discusses two approaches for making HTTP requests in JavaScript - using the built-in XMLHttpRequest object or the newer fetch API. Code examples are provided for making GET requests with both approaches.

Uploaded by

Curry St
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest object or the newer

fetch API. Here's an example of both approaches:

Using XMLHttpRequest:

javascript

Copy code

var xhr = new XMLHttpRequest();

xhr.open('GET', 'https://api.example.com/data', true);

xhr.onload = function() {

if (xhr.status === 200) {

var responseData = JSON.parse(xhr.responseText);

// Process the response data

};

xhr.onerror = function() {

// Handle error

};

xhr.send();

Using fetch:

javascript

Copy code

fetch('https://api.example.com/data')

.then(function(response) {

if (response.ok) {
return response.json();

throw new Error('Network response was not OK');

})

.then(function(data) {

// Process the response data

})

.catch(function(error) {

// Handle error

});

Both methods support various HTTP methods such as GET, POST, PUT, DELETE, etc. You can also add
headers and send data with the request if needed.

You might also like