📜  fetch (1)

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

Fetch API


fetch() is a JavaScript method introduced in ES6 for making asynchronous HTTP requests to APIs and servers. It is a modern replacement for XMLHttpRequest (XHR) which was common in previous versions of JavaScript.

Syntax
fetch(url, {
  method: 'GET/POST/PUT/DELETE',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(data => console.log('Success:', data));
Methods
  • GET: Retrieves data from the server.

  • POST: Sends data to the server to create a new resource.

  • PUT: Sends data to the server to update an existing resource.

  • DELETE: Deletes data from the server.

Headers

Headers are key-value pairs that contain information about the request or response. Some common headers include:

  • Content-Type: specifies the format of the request or response body.

  • Authorization: includes credentials, such as tokens, to access protected resources.

Body

The body of a request contains data being sent to the server. It can be in various formats such as JSON, text, or FormData. When sending data, it needs to be converted to a string using JSON.stringify().

Response

Responses from the server can be handled in various ways including parsing the data as JSON, text or blobs. The json(), text(), and blob() methods can be used to parse the response body.

Examples
Sending a GET request to an API
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Sending a POST request with JSON data
const data = {
  name: 'John Doe',
  age: 25,
};

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Sending a PUT request with text data
const data = 'Hello, world!';

fetch('https://api.example.com/message/123', {
  method: 'PUT',
  headers: {
    'Content-Type': 'text/plain',
    'Authorization': 'Bearer <token>',
  },
  body: data,
})
.then(response => console.log('Success:', response.status))
.catch(error => console.error('Error:', error));
Sending a DELETE request
fetch('https://api.example.com/message/123', {
  method: 'DELETE',
  headers: {
    'Authorization': 'Bearer <token>',
  }
})
.then(response => console.log('Success:', response.status))
.catch(error => console.error('Error:', error));

References:

MDN Web Docs

JavaScript.info