How Do I Make An HTTP Request in Javascript

You might also like

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

How do I make an HTTP request in Javascript

In JavaScript, you can make an HTTP request using the built-in fetch() function or the older
XMLHttpRequest object. Here's an example of how to use fetch() to make a GET request:

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

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error(error));

In this example, fetch() takes a URL as its first argument and returns a Promise that resolves to a
Response object. You can then use the Response object's various methods, such as json() in this
case, to extract the data you need. Finally, you can use the .catch() method to handle any errors
that occur during the request.

If you want to make a POST request or send additional data, you can pass an optional second
argument to fetch() that includes the request method, headers, and body:

fetch('https://example.com/data.json', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify({ key: 'value' })

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error(error));

In this example, we're making a POST request and sending a JSON object as the request body.
We're also specifying a Content-Type header so the server knows how to handle the data.

Using XMLHttpRequest

The XMLHttpRequest (XHR) object is an older way to make HTTP requests in JavaScript. Here's an
example of how to use it to make a GET request:
javascriptCopy code
const xhr = new XMLHttpRequest (); xhr. open ( 'GET' , 'https://example.com/data.json' ); xhr. onload = () =>
{ if (xhr. status === 200 ) { const data = JSON . parse (xhr. responseText ); console . log (data); } else {
console . error ( `Request failed with status ${xhr.status}` ); } }; xhr. send ();

In this example, we create a new XMLHttpRequest object and call its open() method to specify
the request method and URL. We then set the onload event handler, which will be called when
the request completes. Inside the event handler, we check the status code of the response and
parse the response text as JSON data if the status code is 200 (OK).

To make a POST request with XMLHttpRequest, you can use the send() method with a string or
FormData object as the argument:

javascriptCopy code
const xhr = new XMLHttpRequest (); xhr. open ( 'POST' , 'https://example.com/submit' );
xhr. setRequestHeader ( 'Content-Type' , 'application/json' ); xhr. onload = () => { if (xhr. status === 200 ) {
const data = JSON . parse (xhr. responseText ); console . log (data); } else { console . error ( `Request failed with
status ${xhr.status}` ); } }; xhr. send ( JSON . stringify ({ key : 'value' }));

In this example, we set the request method to POST, set the Content-Type header to
application/json, and send a JSON string as the request body.

Using third-party libraries

There are also many third-party libraries available for making HTTP requests in JavaScript, such as
Axios, jQuery, and Superagent. These libraries often provide more advanced features, such as
automatic JSON parsing, error handling, and request cancellation. Here's an example of how to
use Axios to make a GET request:

javascriptCopy code
axios. get ( 'https://example.com/data.json' ) . then ( response => console . log (response. data )) . catch ( error =>
console . error (error));

In this example, we use the get() method of the Axios library to make a GET request and handle
the response using a Promise chain. We use the data property of the response object to extract
the JSON data. If an error occurs, we handle it using the .catch() method.

You might also like