You are on page 1of 1

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

object or the newer fetch() function. Here is an example of how to use fetch():

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

This code sends a GET request to https://example.com/data.json, retrieves the response as


JSON, and logs it to the console. If there is an error, it logs the error to the console as
well.

You can also specify additional options when making the request, such as HTTP
headers or request body data. Here is an example:

javascriptCopy code
fetch ( 'https://example.com/api/data' , { 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));

This code sends a POST request to https://example.com/api/data with a JSON payload of {


"key": "value" } and a Content-Type header of application/json . The response is again
retrieved as JSON and logged to the console, with any errors logged as well.

You might also like