📜  fecth post json - Javascript (1)

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

Fetch Post JSON - Javascript

In modern web development, it's common to use APIs to interact with data. One of the most popular ways to make HTTP requests in JavaScript is using the Fetch API.

In this tutorial, we'll explore how to use the Fetch API to send a POST request with JSON data.

Prerequisites

Before we start, make sure you have a basic understanding of JavaScript and the Fetch API.

Sending a POST request with JSON data

The following example shows how to send a POST request with JSON data using the Fetch API:

fetch('https://example.com/api/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ 
    name: 'John Doe',
    email: 'johndoe@example.com'
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))

In this example, we're sending a POST request to https://example.com/api/data with a JSON object containing name and email properties in the request body.

We also specify the Content-Type header as application/json to indicate that we're sending JSON data in the request.

Once the server responds, we parse the response as JSON using the response.json() method and then log the data to the console.

If there's an error while sending the request or parsing the response, we catch it and log the error to the console.

Conclusion

Sending a POST request with JSON data using the Fetch API is a common task when working with APIs. In this tutorial, we've covered how to do it in JavaScript.

Remember that the Fetch API returns a Promise, so you can use async/await or chained .then() calls to handle the response.