I am currently developing a blogging application using Express, EJS and MongoDB.
One of the main features is an "Add New Post" form with an addPost()
method in the controller;
exports.addPost = (req, res, next) => {
const errors = validationResult(req);
const post = new Post();
post.title = req.body.title;
post.short_description = req.body.excerpt
post.full_text = req.body.body;
console.log(post);
if (!errors.isEmpty()) {
req.flash('danger', errors.array());
req.session.save(() => res.render('admin/addpost', {
layout: 'admin/layout',
website_name: 'MEAN Blog',
page_heading: 'Dashboard',
page_subheading: 'Add New Post',
post: post
}));
} else {
post.save(function(err) {
if (err) {
console.log(err);
return;
} else {
req.flash('success', "The post was successfully added");
req.session.save(() => res.redirect('/dashboard'));
}
});
}
}
The form view:
<form action="./post/add" method="POST" class="mb-0">
<div class="form-group">
<input type="text" class="form-control" name="title" value="<%= req.body.title %>" placeholder="Title" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="excerpt" value="<%= req.body.excerpt %>" placeholder="Excerpt" />
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="body" placeholder="Full text">
<%= req.body.title%>
</textarea>
</div>
<div class="form-group mb-0">
<input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
</div>
</form>
If certain required fields are filled in but not all, the form does not retain the data when re-rendered. The expected data from the submitted fields should persist even for the empty required fields.
Even though the generated HTML shows the correct values like title and excerpt, the form seems to reset them after submission:
{
updated_at: 2020-03-18T10:49:17.199Z,
created_at: 2020-03-18T10:49:17.199Z,
_id: 5e71fcbe7fafe637d8a2c831,
title: 'My Great Post',
short_description: '',
full_text: ''
}
Here's the link to the image showing this issue: https://i.stack.imgur.com/C1wQz.png
Any insights on what might be causing this behavior?
UPDATE:
This snippet displays the output HTML code of the form with cleared input values even when they were initially filled:
<form action="./post/add" method="POST" class="mb-0">
<div class="form-group">
<input type="text" class="form-control" name="title" value="" placeholder="Title">
</div>
<div class="form-group">
<input type="text" class="form-control" name="excerpt" value="" placeholder="Excerpt">
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="body" placeholder="Full text"></textarea>
</div>
<div class="form-group mb-0">
<input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
</div>
</form>