The Fetch API in JavaScript provides a modern interface for fetching resources asynchronously across the network. It provides a simpler and more flexible way to perform HTTP requests compared to traditional XMLHttpRequest (XHR) requests.

Here is an example of using the Fetch API to fetch data from a URL:

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

In this example, we are fetching data from the URL 'https://jsonplaceholder.typicode.com/users' and using the .json() method to parse the response as JSON. We then log the resulting data to the console. If there is an error during the fetch, we catch it and log the error to the console.

The Fetch API also provides a way to configure the request with options like headers, HTTP method, and body data. Here is an example of using options with the Fetch API:

const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John Doe',
    email: 'johndoe@example.com'
  })
};

fetch('https://example.com/api/users', options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we are sending a POST request to 'https://example.com/api/users' with a JSON payload containing a name and email. We configure the request with the options object, which specifies the HTTP method, headers, and body data. We then parse the response as JSON and log the resulting data to the console. If there is an error during the fetch, we catch it and log the error to the console.

fetch api js

原文地址: http://www.cveoy.top/t/topic/bfLG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录