I am using Node.js and I want to send a request which contains an input value to the server when a button is pressed.
So here's my HTML code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input id="input" action="/onclick" autocomplete="off">
<button id="button">Send</button>
<script>
let input = document.getElementById('input');
document.getElementById('button').addEventListener('click', (event) => {
event.preventDefault();
let value = input.value;
if (value) {
let data = {};
data.title = 'getValue',
data.message = value;
$.ajax({
url:'/onclick',
data: JSON.stringify(data),
type: 'POST',
success: (responseData) => {
console.log('Success!');
},
});
input.value = null;
}
});
</script>
</body>
</html>
And here's my server.js :
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/onclick', (req, res) => {
console.log('body: '+ JSON.stringify(req.message));
res.send(req.message);
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
The code doesn't throw any error (it returns Success! in browser console) but the problem is that in the Node.js shell it sends body: undefined instead of the input value.
Do you know how to fix that ?
Thanks in advance,
Add this line in your server.js to access the request body:
app.use(express.json());
And use req.body instead of req.message to access the request body