JavaScript - send POST JSON fetch() request

7 points
Created by:

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

Practical example:

const sendData = async (requestUrl, requestData) => {
    const response = await fetch(requestUrl, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        body: JSON.stringify(requestData)  // request payload
    return await response.json();

// Usage example:

const data = {
    username: 'john',
    password: 'secret_password'

const responseData = await sendData('/path/to/backend', data); // using await call it in async method


'Accept': 'application/json'tells to backend about accepted response type
(we accept JSONs only)
'Content-Type': 'application/json'tells to backend about sent body type
(called payload type too)
body: JSON.stringify(requestData)sets converted JavaScript object to JSON as request body
(request payload)
await response.json()converts response JSON to JavaScript object
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.

❤️💻 🙂