Languages
[Edit]
EN

JavaScript - send POST JSON fetch() request

7 points
Created by:
Aisha
418

In this short article, we would like to show how to send JSON data in POST request using fetch() function in JavaScript.

Quick solution:

 

Practical example

Edit

In this section, you can find reusable function that lets to send and receive object.

In the below example:

  1. we use POST request that lets to send some data as request body,
  2. we send object that contains username and password:
  3. it is necessary to convert object to JSON before request:
    Note: request body can be called as request payload or request content too

Practical example:

Where:

'Accept': 'application/json'

tells to backend about accepted response type
(we use await response.json(), so accepted are JSONs only)

'Content-Type': 'application/json'tells to backend about sent body type in the request
body: JSON.stringify(requestData)sets converted JavaScript object to JSON as request body
await response.json()converts response JSON to JavaScript object

 

References

Edit
  1. fetch() - MDN Docs 
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join