DEV Community

Cover image for Master the Basic Art of Making HTTP Requests with Javascript
Kamran Ahmad
Kamran Ahmad

Posted on • Edited on

Master the Basic Art of 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.

Top comments (2)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Couple of tips:

  1. Specify the language of your code blocks immediately after the 3 opening ticks to get colorized code.
  2. Maybe re-title this as "Master the basics..." and then make it the first of a series that explains in more detail the fetch() function. For example, using it with a Request object instead of just an URL.

Colorized code block 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
Collapse
 
ikamran01 profile image
Kamran Ahmad

done now thanks!