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.
1. Get JSON from requests example
Note: it is required to add external library to run below example, so use:
npm install express
JSON received from the client in the POST request:
{
"title": "example title",
"text": "example text"
}
Practical code:
const express = require('express');
const port = 3000;
const app = express();
app.use(express.json()); // middleware to parse JSON
app.post('/tasks/', (request, response) => {
const title = request.body.title; // title = "example title"
const text= request.body.text; // text = "example text"
// Here we can sends a query to the database
if (error) {
response.status(500).send({ error: error });
} else {
response.sendStatus(200)
}
});
app.listen(port, () => {
console.log(`server is listening at http://localhost:${port}`);
});
Note: to read the JSON contained in the request, we must use
express.json()
middleware.
2. Pure JavaScript (Vanilla JS) AJAX POST request
The following is an example execution of a fetch
method that sends JSON via POST request.
<!DOCTYPE html>
<html>
<body>
<script>
var task = {
title: 'example title',
text: 'example text'
}
fetch('/tasks', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(task),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
</script>
</body>
</html>