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:

const requestUrl = '/path/to/backend';

const requestData = {
    username: 'john',
    password: 'P@ssword'
};

const response = await fetch(requestUrl, {
	method: 'POST',
	headers: {
		'Accept': 'application/json',
		'Content-Type': 'application/json'
	},
	body: JSON.stringify(requestData)  // called request payload or request content too
});

const responseData = await response.json();

 

Practical example

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:
    const requestData = {
        username: username,
        password: password
    };
  3. it is necessary to convert object to JSON before request:
    const requestJson = JSON.stringify(requestData);
    Note: request body can be called as request payload or request content too

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)  // called request payload or request content too
    });
    return await response.json();
};


// Usage example:

const sendUser = async (username, password) => {
    const requestData = {
        username: username,
        password: password
    };
    const responseData = await sendData('/path/to/backend', requestData);
    return responseData;
};

sendUser('john', 'P@ssword'); // you can add await keyword in async method

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

  1. fetch() - MDN Docs 
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