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.
1. Express.js POST methods example
In this section, we use Express.js to handle POST requests.
index.js
const express = require('express'); // installation: npm install express
const port = 3000;
const app = express();
app.post('/examples', (request, response) => {
const data = request.body;
// create/update a resource
response.send('put your changed data here');
});
app.listen(port, () => {
console.log(`server is listening at http://localhost:${port}`);
});
To run the server use:
node index.js
Output:
server is listening at http://localhost:3000
2. Pure JavaScript (Vanilla JS) AJAX POST request
The following is an example execution of a fetch
method that sends POST requests.
<!DOCTYPE html>
<html>
<body>
<script>
var bodyData = 'text';
fetch('/examples', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: bodyData,
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
</script>
</body>
</html>