📜  fetch API javascript sintax - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:10.511000             🧑  作者: Mango

Fetch API JavaScript Syntax

The Fetch API is an interface in JavaScript for fetching resources (e.g. data) asynchronously across the network (e.g. via HTTP).

Syntax
fetch(url[, options])
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
Parameters
  • url: The URL for the resource to be fetched.
  • options (optional): An object containing additional parameters for the request (e.g. headers, method, body).
Return value

A Promise that resolves to a Response object.

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

This example fetches data from "https://api.example.com/data", converts the response to JSON format, and logs the resulting object to the console.

Options
Method

The HTTP method (e.g. GET, POST) used for the request is specified using the method option. By default, it is set to "GET".

fetch('https://api.example.com/data', {
  method: 'POST',
  body: JSON.stringify({ username: 'example', password: 'password'})
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

This example sends a POST request to "https://api.example.com/data" with a JSON payload containing a username and password.

Headers

Custom headers can be included in the request using the headers option.

fetch('https://api.example.com/data', {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer myToken'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

This example includes custom headers "Content-Type" and "Authorization" with values "application/json" and "Bearer myToken" respectively.

Body

The body option is used to send data in the request body. It can be a FormData, Blob, ArrayBuffer, or a JSON string.

fetch('https://api.example.com/data', {
  method: 'POST',
  body: JSON.stringify({ username: 'example', password: 'password'})
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

This example sends a JSON payload containing a username and password in the request body.

Error handling

Errors can be caught using the catch method.

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.log(error));

This example throws an error if the response status is not okay (e.g. 404 Not Found).