📜  js fetch api - Javascript (1)

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

JS Fetch API - JavaScript

Introduction

Fetch API is a modern interface for accessing and manipulating HTTP requests and responses in JavaScript. It is a part of the Web API specification and is supported in all major browsers like Google Chrome, Mozilla Firefox, Safari, and more.

Using Fetch API

The fetch API uses Promises, which allow us to handle the response asynchronously. Here is an example of how to use the fetch() method:

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

In the above example, we fetch data from the API endpoint https://example.com/data. The response is converted to JSON using the json() method and then logged to the console. Finally, we catch any errors that may occur during the request.

Fetch Request Options

The fetch() method has several other options that can be used to customize the fetch request. Here are some examples:

Adding Headers
fetch('https://example.com/data', {
  headers: {
    'Content-Type': 'application/json'
  }
})

In the above example, we add a header to the request that specifies the content type as JSON.

Adding Query Parameters
fetch('https://example.com/data?param1=value1&param2=value2')

Here, we add two query parameters, param1 and param2, with their respective values to the URL.

POST Request
fetch('https://example.com/data', {
  method: 'POST',
  body: JSON.stringify({ data: 'example' }),
  headers: {
    'Content-Type': 'application/json'
  }
})

In the above example, we make a POST request to the endpoint with JSON data included in the request body.

Conclusion

Fetch API provides an easy, modern way to make HTTP requests from JavaScript. With its asynchronous and customizable options, it allows developers to handle responses with ease and flexibility.