Hi this is my first Webproject for school so I might not get everything right away.
When I submit the form on the client-side, the input values from the form fields are being sent to the server as "undefined," and so that I am not able to store the data or update the contributions div with the new entry.
The server-side code is implemented using Node.js and Express, while the client-side code uses HTML, JavaScript, and CSS.
<body>
<header>
<script>
$(function() {
$('header').load('navbar.html');
});
</script>
</header>
<div id="container">
<form id = "kontaktFormular" action="/forum/beitrag" method = 'POST'>
<h1>Forum</h1>
<input id ="thema" type="text" name="tit" placeholder="Thema" required>
<input id ="beitragTextfeld" type="text" name="contr" placeholder="Sagen Sie uns Ihre Meinung!" required>
<button type="submit">Abschicken</button>
</form>
<div id=" beitraege">
<p id = contributions></p>
</div>
<script>
// Function to fetch and update the entries
async function updateEntries() {
const response = await fetch('/forum/beitrag');
const entries = await response.json();
const entryList = document.getElementById('contributions');
entryList.innerHTML = '';
entries.forEach(entry => {
const listItem = document.createElement('li');
listItem.textContent = `Date:${entry.datum} Title: ${entry.thema}, Contribution: ${entry.beitrag}`;
entryList.appendChild(listItem);
});
}
window.addEventListener('load', updateEntries);
document.getElementById('kontaktFormular').addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const tit = formData.get('tit');
const contr = formData.get('contr');
const response = await fetch(event.currentTarget.action, {
method: 'POST',
body: formData
});
const updatedEntries = await response.json();
updateEntries(updatedEntries);
});
</script>
</div>
</body>
Serverside:
const express = require('express');
const app = express();
const path = require('path');
const port = 8000;
app.use(express.urlencoded({extended: false}));
app.use(express.static('.'));
app.use(express.json());
app.get('/forum/beitrag', (req, res) => {
res.send(entryData);
console.log("posted");
});
let entryData = [
{datum: "10.Juni.2023", thema: "mein beitrag", beitrag: "digga warum geht das nicht"}];
app.post('/forum/beitrag', (req, res) => {
const { tit, contr } = req.body;
console.log({ tit, contr });
const newEntry = {datum: createDate(), thema: tit, beitrag: contr};
entryData.push(newEntry);
res.json(entryData);
});
app.get('/logout', (req, res) => {
})
app.listen(port, () => {
console.log(` app listening on port ${port}`)
})
I’ve tried to check for typos and checked if I’m using the right modules.
When I’ve console.loggged the received data on the Serverside I can see that it’s empty/both values are undefined.
2
Answers
Thanks! I've now come up with the following:
After extracting the items, you can build an object and pass it to
JSON.stringify
. Proof-of-concept: