EN
Express.js - send json to node server
0 points
In this article, we would like to show you how to get JSON from requests in Express.js.
The request data are passed in the request.body
property.
Note: it is required to add external library to run below example, so use:
xxxxxxxxxx
1npm install express
JSON received from the client in the POST request:
xxxxxxxxxx
1
{
2
"title": "example title",
3
"text": "example text"
4
}
Practical code:
xxxxxxxxxx
1
const express = require('express');
2
3
const port = 3000;
4
const app = express();
5
6
app.use(express.json()); // middleware to parse JSON
7
8
app.post('/tasks/', (request, response) => {
9
const title = request.body.title; // title = "example title"
10
const text= request.body.text; // text = "example text"
11
// Here we can sends a query to the database
12
13
if (error) {
14
response.status(500).send({ error: error });
15
} else {
16
response.sendStatus(200)
17
}
18
});
19
20
app.listen(port, () => {
21
console.log(`server is listening at http://localhost:${port}`);
22
});
Note: to read the JSON contained in the request, we must use
express.json()
middleware.
The following is an example execution of a fetch
method that sends JSON via POST request.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
var task = {
7
title: 'example title',
8
text: 'example text'
9
}
10
11
fetch('/tasks', {
12
method: 'POST',
13
headers: {
14
'Content-Type': 'application/json',
15
},
16
body: JSON.stringify(task),
17
})
18
.then((response) => response.json())
19
.then((data) => {
20
console.log('Success:', data);
21
})
22
.catch((error) => {
23
console.error('Error:', error);
24
});
25
26
</script>
27
</body>
28
</html>
29