How to make an HTTP request in Javascript

How do I make an HTTP request in Javascript?



You can make an HTTP request in JavaScript using the built-in XMLHttpRequest object or the newer fetch() function. Here's an example using fetch():

****************************************

1
2
3
4
fetch('https://example.com/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

**************************************** 

This code sends a GET request to https://example.com/api/data and logs the JSON response to the console. If an error occurs, it will be logged to the console as well.

If you need to send data along with the request, you can pass an options object to fetch() with a method property set to 'POST' or 'PUT' and a body property containing the data to be sent.

***************************************

const data = { name: 'John', age: 30 };

fetch('https://example.com/api/data', {
  method: 'POST',
  body: JSON.stringify(data),
  headers: { 'Content-Type': 'application/json' }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

***************************************

This code sends a POST request with the JSON-serialized data object in the request body and sets the 'Content-Type' header to 'application/json'. The response is logged to the console as before.

-------------------------------------------------------------

In conclusion, we hope you enjoyed reading our post and found it informative and valuable. We put a lot of effort into creating high-quality content and would love to hear your thoughts and feedback. So, please do leave a comment and let us know what you think. Additionally, we invite you to visit our website www.javaoneworld.com to read more beautifully written posts on various topics related to coding, programming, and technology. We are constantly updating our website with fresh and valuable content that will help you improve your skills and knowledge. We are excited to have you as a part of our community, and we look forward to connecting with you and providing you with more informative and valuable content in the future. 

Happy coding!✌✌

No comments:

Post a Comment