Express.js application bug: form filed values do not persist

喜夏-厌秋 提交于 2020-04-11 02:02:31

问题


I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.

There is an "Add New Post" form of course, 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>

Suppose some of the required form fields are filed-in, but not all of them.

The form view is rendered again, with error messages for the empty required fields. But the required fields that are not empty should persist their data. But they do not.

Using this syntax does not work either <input type="text" class="form-control" name="title" value="<%= post.title %>" placeholder="Title" /> even though the line console.log(post) shows this in the console, as expected:

{
  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: ''
}

What am I missing?

UPDATE:

The generated HTML of the form:

<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>

回答1:


There are few things you'll have to change on your controller and view, I have mentioned both changes below

On your controller

exports.addPost = (req, res, next) => {
    var form = {
        titleholder: req.body.title,
        excerptholder : req.body.excerpt,
        bodyholder: req.body.body
    };
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
            req.flash('danger', errors.array())
            //req.session.save(() => res.redirect('../addpost'));
            res.render('admin/addpost',{
                layout: 'admin/layout',
                website_name: 'MEAN Blog',
                page_heading: 'Dashboard',
                page_subheading: 'Add New Post',
                form:form});
    } else {

Code after else is same as you already have, I have added a form object and changed your res.redirect to res.render

And this will be the code for your view

<div class="col-sm-7 col-md-8 col-lg-9">
    <div class="card">
        <div class="card-header d-flex px-2">
            <h6 class="m-0"><%= page_subheading %></h6>
        </div>
        <div class="card-body p-2">
            <form action="./post/add" method="POST" class="mb-0">               
                <div class="form-group">
                        <input type="text" class="form-control" name="title" value="<%= typeof form!='undefined' ? form.titleholder : '' %>" placeholder="Title" />
                </div>

                <div class="form-group">
                        <input type="text" class="form-control" name="excerpt" value="<%= typeof form!='undefined' ? form.excerptholder : '' %>" placeholder="Excerpt" />
                </div>

                <div class="form-group">
                        <textarea rows="5" class="form-control" name="body" placeholder="Full text"><%= typeof form!='undefined' ? form.bodyholder : '' %></textarea>
                </div>

                <div class="form-group mb-0">
                    <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
                </div>
        </form>
  </div>
    </div>
</div>

values for value attribute is changed. I have also created a pull request for your github project.




回答2:


This should work.

                <form action="./post/add" method="POST" class="mb-0">
                    <div class="form-group">
                            <input type="text" class="form-control" name="title" value="<%=post && post.title? post.title : ''%>" placeholder="Title" />
                    </div>

                    <div class="form-group">
                            <input type="text" class="form-control" name="excerpt" value="<%=post && post.short_description? post.short_description : ''%>" placeholder="Excerpt" />
                    </div>

                    <div class="form-group">
                            <textarea rows="5" class="form-control" name="body" placeholder="Full text"><%=post && post.full_text? post.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>



回答3:


<div class="form-group">
    <input type="text" class="form-control" name="title" placeholder="Title" value="<%= typeof title != 'undefined' ? title: '' %>">
</div>

and the same goes for your excerpt and textarea




回答4:


The complete working code adding posts ca be seen below.

In the controller:

exports.addPost = (req, res, next) => {

    var form = {
        titleholder: req.body.title,
        excerptholder: req.body.excerpt,
        bodyholder: req.body.body
    };

    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;

    if (!errors.isEmpty()) {
        req.flash('danger', errors.array())
        res.render('admin/addpost', {
            layout: 'admin/layout',
            website_name: 'MEAN Blog',
            page_heading: 'Dashboard',
            page_subheading: 'Add New Post',
            form: form
        });
    } 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'));
            }
        });
    }
}

In the view:

<form action="/dashboard/post/add" method="POST" class="mb-0">
    <div class="form-group">
        <input type="text" class="form-control" name="title" value="<%= typeof form!='undefined' ? form.titleholder : '' %>" placeholder="Title" />
    </div>

    <div class="form-group">
        <input type="text" class="form-control" name="excerpt" value="<%= typeof form!='undefined' ? form.excerptholder : '' %>" placeholder="Excerpt" />
    </div>

    <div class="form-group">
        <textarea rows="5" class="form-control" name="body" placeholder="Full text">
            <%= typeof form!='undefined' ? form.bodyholder : '' %>
        </textarea>
    </div>

    <div class="form-group mb-0">
        <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success">
    </div>
</form>


来源:https://stackoverflow.com/questions/60721476/express-js-application-bug-form-filed-values-do-not-persist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!