Надсилання HTTP-запиту

JavaScript:
Надсилання HTTP-запиту

How to: (Як зробити:)

Here’s how to send a GET request using the fetch API to grab some JSON data and then post data using fetch.

// GET request for remote image in node.js
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.error('Error:', err));

// POST request using fetch()
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.error('Error:', err));

Deep Dive (Занурення у Деталі):

Long before fetch, we had XMLHttpRequest. It did the job but was clunky. fetch is the modern, promise-based evolution of web requests. Alternatives? Yes, many use axios for more features out of the box. Behind the scenes, fetch wraps around the low-level HTTP protocol, dealing with strings and streams neatly, so you don’t have to.

Historically, sending requests from the browser was limited by the same-origin policy - a security measure. But now, with CORS (Cross-Origin Resource Sharing), we can request resources from different origins, given the server allows it.

See Also (Дивіться Також):