I have implemented a post request to add input data from a form. The entered data is stored in an array variable burg
and then displayed on my index.handlebars view. Everything works as intended, but when the page is refreshed without any input in the form, the array duplicates the previously added data. I am puzzled about how to prevent this behavior upon refresh, ensuring that the array remains unchanged while only clearing the form input and display area where burg
is shown.
Here is the code snippet for displaying the array list and form in index.handlebars:
<ul>
{{#each burg}}
<li>{{this}}</li>
{{/each}}
</ul>
<form class="form-group" method="post" action="/">
<label>Add to Eat</label>
<input type="text" class="form-control" id="add" name="add" placeholder="Unique Burger Details">
<button type="submit" class="btn btn-primary btn-md" id="add-btn">
<span class="fa fa-book"></span> Add Ur Burger</button>
</form>
Below is the segment of controller.js:
const express = require('express');
const router = express.Router();
let burg = [];
router.post("/", (req, res, next) => {
burg.push(req.body.add);
res.render("index", {burg});
res.end;
});
Finally, here is a portion of server.js:
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/", function (req, res) {
res.render("index", {burg});
});
app.use("/", burgerRouter);