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:
xxxxxxxxxx
1
const requestUrl = '/path/to/backend';
2
3
const requestData = {
4
username: 'john',
5
password: 'P@ssword'
6
};
7
8
const response = await fetch(requestUrl, {
9
method: 'POST',
10
headers: {
11
'Accept': 'application/json',
12
'Content-Type': 'application/json'
13
},
14
body: JSON.stringify(requestData) // called request payload or request content too
15
});
16
17
const responseData = await response.json();
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
:xxxxxxxxxx
1const requestData = {
2username: username,
3password: password
4};
- it is necessary to convert object to JSON before request:
xxxxxxxxxx
1const requestJson = JSON.stringify(requestData);
Note: request
body
can be called as request payload or request content too
Practical example:
xxxxxxxxxx
1
const sendData = async (requestUrl, requestData) => {
2
const response = await fetch(requestUrl, {
3
method: 'POST',
4
headers: {
5
'Accept': 'application/json',
6
'Content-Type': 'application/json'
7
},
8
body: JSON.stringify(requestData) // called request payload or request content too
9
});
10
return await response.json();
11
};
12
13
14
// Usage example:
15
16
const sendUser = async (username, password) => {
17
const requestData = {
18
username: username,
19
password: password
20
};
21
const responseData = await sendData('/path/to/backend', requestData);
22
return responseData;
23
};
24
25
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 |