EN
Express.js - AJAX POST request
0 points
In this article, we would like to show you how to make AJAX POST requests in Express.js.
In this section, we use Express.js to handle POST requests.
index.js
xxxxxxxxxx
1
const express = require('express'); // installation: npm install express
2
3
const port = 3000;
4
const app = express();
5
6
app.post('/examples', (request, response) => {
7
const data = request.body;
8
// create/update a resource
9
10
response.send('put your changed data here');
11
});
12
13
app.listen(port, () => {
14
console.log(`server is listening at http://localhost:${port}`);
15
});
To run the server use:
xxxxxxxxxx
1
node index.js
Output:
xxxxxxxxxx
1
server is listening at http://localhost:3000
The following is an example execution of a fetch
method that sends POST requests.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
var bodyData = 'text';
7
8
fetch('/examples', {
9
method: 'POST',
10
headers: {
11
'Content-Type': 'text/plain',
12
},
13
body: bodyData,
14
})
15
.then((response) => response.json())
16
.then((data) => {
17
console.log('Success:', data);
18
})
19
.catch((error) => {
20
console.error('Error:', error);
21
});
22
23
</script>
24
</body>
25
</html>