如何使用导入的路由器将提交的表单输入输出到EJS

问题描述 投票:0回答:1

[当前,我想提交表单,之后,标题和描述应该像在Todo应用程序中那样输出,但是为什么在我的情况下它不起作用。

//server.js
const postsRoute = require('./routes/posts');

app.use('/posts', postsRoute);

//router/posts.js
router.post('/', async(req, res) => {
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    });

    try {
        const postSaved = await post.save()
        res.json(postSaved);
        res.render('productPage.ejs')
    } catch(err) {
        res.json({ message: err })
    }
});
<form action="/posts" method="POST">
    <div>
      <label for="say">What greeting do you want to say?</label>
      <input name="title" id="say">
    </div>

    <div>
      <label for="to">Who do you want to say it to?</label>
      <input name="description" id="to">
    </div>

    <div>
      <button type="submit">Send my greetings</button>
    </div>
 </form>
node.js mongodb express post ejs
1个回答
0
投票

为了用输入值呈现页面,您可以添加此行'title': req.body.title,而对您的description也是如此。>>

 try {
            const postSaved = await post.save();
            console.log(postSaved)  
            res.render('productPage.ejs', { 'title': req.body.title , 'description':req.body.description })
        } catch(err) {
            res.json({ message: err })
        }

和您的productPage.ejs看起来像这样

this is Title <%= title %> <br>
this is description <%= description %> 
© www.soinside.com 2019 - 2024. All rights reserved.