ParallelDesk
Login

How do I make an HTTP request in Javascript?

Paralleldesk 20 December 2022

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object, or you can use the fetch() function.

Here's an example using XMLHttpRequest:

Copy codevar xhr = new XMLHttpRequest(); xhr.open('GET', 'https://www.example.com/api/data'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();

Here's an example using fetch():

Copy codefetch('https://www.example.com/api/data') .then(response => response.text()) .then(data =>console.log(data)) .catch(error =>console.error(error));

Both examples make a GET request to the specified URL and log the response to the console. You can replace 'GET' with 'POST', 'PUT', or any other HTTP method to make a different type of request. You can also add additional options, such as headers or a request body, by passing an object as the second argument to open() or fetch().

Keep in mind that making HTTP requests from JavaScript is subject to the same origin policy, which means that you can only make requests to URLs on the same domain as the current page. If you need to make a request to a different domain, you may need to use a server-side proxy or enable CORS (Cross-Origin Resource Sharing) on the server.