How do I make an HTTP request in Javascript?

You can make an HTTP request in JavaScript using the built-in fetch function or by creating an instance of the XMLHttpRequest object. Here’s an example of how to use fetch to make an HTTP GET request:

In this example, we’re using the fetch function to make an HTTP GET request to the URL ‘https://example.com/data’. We’re then using the then method to parse the response as JSON and log the resulting data to the console. If there’s an error, we’re using the catch method to log the error to the console.
If you prefer to use the XMLHttpRequest object, you can do so like this:

In this example, we’re creating a new instance of XMLHttpRequest and using the open method to specify the HTTP method and URL. We’re then using the onload method to parse the response as JSON and log the resulting data to the console if the HTTP status code is 200. If there’s an error, we’re using the onerror method to log the error to the console. Finally, we’re using the send method to send the request.

You can also send other types of HTTP requests, such as POST or PUT requests, by passing additional options to the fetch function. Here’s an example of sending a POST request with some data:

In this example, we’re sending a POST request to the same URL with some JSON data in the request body. We also specify the Content-Type header to let the server know that we’re sending JSON data. The JSON.stringify method is used to convert the JavaScript object to a JSON string that can be sent in the request body.

Leave a Reply

Your email address will not be published. Required fields are marked *