Menu Close

Making HTTP Requests with Javascript

Making HTTP Requests with Javascript

You can use the fetch() function to make HTTP requests in JavaScript. The fetch() function is a modern way to make HTTP requests in JavaScript, and it’s supported by most modern browsers.

Here’s an example of how you can use fetch() to make an HTTP GET request to an API endpoint:

fetch('https://api.example.com/endpoint')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
Enter fullscreen mode

Exit fullscreen mode

This example makes a GET request to the specified API endpoint and logs the response data to the console. The response.json() method parses the response data as JSON, and the .then() method is used to handle the response data asynchronously. The .catch() method is used to catch any errors that occur during the request.

You can also use fetch() to make POST requests, or requests with other HTTP methods, by specifying the method in the options object that you pass to fetch(). For example:

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

Exit fullscreen mode

This example makes a POST request to the specified API endpoint with a JSON payload in the request body. The Content-Type header is set to application/json to specify the format of the request body.

View Source
Posted in JavaScript