📜  javascript fetch mehtod - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:37.512000             🧑  作者: Mango

Javascript Fetch Method

Fetch is a modern web API that provides a simple interface to fetch and manipulate resources across the network. The Fetch API is a low-level interface which enables fetching resources asynchronously via HTTP or other network protocols.

The fetch() method is used to make asynchronous requests to the server and receives an HTTP response. It can be used to request files, APIs, or any other resources that are accessible over the network.

Basic Syntax
fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
Parameters
  • url : A string representing the URL of the resource you want to fetch.
  • options : An object containing request options like method, headers, body, cache, and mode. These options are optional, but they allow you to customize the request.
Return value

The fetch() method returns a Promise that resolves to the Response of the request. This Response object represents the response to the request made.

Examples

Fetching JSON Data

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))

In this example, we are fetching a JSON data from an API using the fetch() method. We are converting the response to JSON data using the .json() method. Finally, we are logging the data to the console.

Sending POST Request

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

In this example, we are sending a POST request to an API endpoint. We are setting the request method to POST and providing the request body as a JSON string using the JSON.stringify() method. We are also setting the Content-Type header to application/json. Finally, we are logging the response to the console.

Conclusion

The fetch() method is a powerful feature of modern web development that enables developers to make asynchronous requests to the server and handle responses more efficiently. It supports a wide range of request options and is easy to use. Check out MDN web docs for more information on using the fetch() method.