首页 > 解决方案 > 如何使用 Pug 作为模板引擎在 nodeJs/Express 中发出补丁请求

问题描述

请我正在使用 nodejs/express、mongoDB 和使用 Pug 开发一个博客站点。我目前正在尝试使用 Pug 的补丁请求向我的帖子数据发送评论,但遇到了一些问题。以下是详细信息。

我在根目录中有一个服务器文件夹,其中有一个blogPost.js文件。此 blogPost.js 文件包含以下代码

...
router.patch('/comment/:postId', async (req, res) => {
    try{
    const updatedPostComment = await BlogPost.updateOne({ _id: req.params.postId }, 
        {
            $push: {
                comment: [{
                    author: req.body.comment.author,
                    text: req.body.comment.text   
            }]}      
            });
        res.json(updatedPostComment);
            }catch (err) {
                res.json({ message: err });
    }
});
...

当我用邮递员测试它时,这段代码运行良好。我可以向邮递员发出补丁请求,以根据帖子的 ID 为 mongoDb 中的特定帖子更新我的数据中的评论数组。

我在根文件夹中还有一个index.js文件,其中包含以下代码,

...
//Set Pug
app.set('view engine', 'pug');

//Pug Routes/Request
app.get('/', async (req, res) => {
    const query = await axios.get('http://localhost:1800/post');
    res.render('index', { posts: query.data });
  });
...
app.patch('/comment/:id', async (req, res) => {
    const query = await axios.patch('http://localhost:1800/post/comment/' + req.params.id);
    res.render('comment', { 
      id: req.params.id
     });
  });

// Connect to DB
mongoose.connect( 
    process.env.DB_CONNECTION, 
    {  useNewUrlParser: true ,
       useUnifiedTopology: true, 
    },
    () => console.log('Connected to DB')
);

const port = process.env.PORT || 1800;
app.listen(port, () => console.log(`server started on port ${port}`));

最后,我的视图文件夹中有index.pug文件,该文件在下面的代码中有一个表单

extends layout
block content
    br
    - const post = posts[0]

        div
            form(action=`http://localhost:1800/post/comment/${post._id}` method="patch" class="was-validated shadow font-weight-bold")
                .form-group.mx-3
                    label(for="" class="text-uppercase") Author
                    input(type="text" name="author" id="" class="form-control" required)
                .form-group.mx-3
                    label(for="" class="text-uppercase") Comment
                    input(type="text" name="text" id="" class="form-control" required)
                .text-center
                    input(type="submit" value="Send Post" class="btn btn-primary mt-4 mb-5")

当我尝试从表单发送补丁请求时,它不像邮递员那样工作。这是我在将文本发送到表单时在控制台和 url 中遇到的错误

获取http://localhost:1800/post/comment/5ebcf79271217d299c6d2f1eauthor=Kwabena+Attakora+Frimpong&text=thank+you+God 404 错误

请问我错过了什么。是来自表单操作还是 indexjs 文件中缺少某些内容。恳求我是堆栈,我需要帮助。谢谢您的支持。

标签: node.jspug

解决方案


推荐阅读