DEV Community

swetha palani
swetha palani

Posted on

Fetch in JavaScript

What is Fetch?

The fetch() method in JavaScript is used to make HTTP requests (like GET, POST, PUT, DELETE) from the browser to a server.

  • It returns a Promise.
  • The response is usually converted to JSON for easy handling.

Syntax

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
Enter fullscreen mode Exit fullscreen mode
  • url → The address of the resource (API endpoint).
  • options → Optional (method, headers, body, etc.).

Example:

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log("Error:", error));
Enter fullscreen mode Exit fullscreen mode

Output:

{
  "userId": 1,
  "id": 1,
  "title": "Sample title",
  "body": "Sample body text..."
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • fetch() is a modern way to make API calls in JavaScript.
  • It works with Promises and supports async/await.
  • You can use it for GET, POST, PUT, DELETE requests easily.

Top comments (0)