How do I make an HTTP request in Javascript?

How do I make an HTTP request in Javascript?

To make an HTTP request in JavaScript, you can use the built-in fetch() method or the older XMLHttpRequest() object. Here's an example using fetch():

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 and logs the response data to the console as a JSON object. If there's an error, it logs the error message instead.

You can also customize the request by passing in additional options to the fetch() function, such as headers and request method. Here's an example:

fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},



0
0
0.000
0 comments