EN
JavaScript - send POST JSON fetch() request
7
points
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:
- we use
POST
request that lets to send some data as requestbody
, - we send object that contains
username
andpassword
:const requestData = { username: username, password: password };
- 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 |
'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 |