Advertisement
CodeCrusader

Make HTTP Request JavaScript

Jan 2nd, 2023 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.88 KB | Source Code | 0 0
  1. // There are many ways to make an HTTP request in JavaScript, but the most common way is using the XMLHttpRequest object. Here is an example of how to make a GET request to a server using XMLHttpRequest:
  2.  
  3. var xhr = new XMLHttpRequest();
  4. xhr.open('GET', 'https://www.example.com/api/endpoint');
  5. xhr.send();
  6. To handle the response from the server, you can set up an event handler for the onload event of the XMLHttpRequest object:
  7.  
  8. xhr.onload = function() {
  9.   if (xhr.status === 200) {
  10.     console.log('Success:', xhr.responseText);
  11.   } else {
  12.     console.error('Error:', xhr.statusText);
  13.   }
  14. };
  15.  
  16. // This will log the server's response to the console if the request was successful (HTTP status code 200) or log an error message if it was not.
  17.  
  18. // There are also other ways to make HTTP requests in JavaScript, such as using the fetch function or third-party libraries like Axios or jQuery.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement