node.js - 如何使用 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 中遇到的错误
请问我错过了什么。是来自表单操作还是 indexjs 文件中缺少某些内容。恳求我是堆栈,我需要帮助。谢谢您的支持。
解决方案
推荐阅读
- html - 如何正确居中引导图标并在其与上方的 P 元素之间添加空格?
- machine-learning - 如何在 XGBRegressor 中选择 'n_estimators' 和 'seed' 的值?
- javascript - 如何在全日历中显示所有事件而不受范围限制?
- laravel - 如何在 Laravel 中保留所有子类别?
- flutter - 如何将 Latlng 值转换为双精度类型
- c# - 基本类型为IdentittyUser时如何映射鉴别器列?
- redis - 带模式的 DELTE Redis 键
- node.js - Dialogflow Webhook 调用失败。错误:[ResourceName 错误] 路径 '' 与模板不匹配
- c# - 如何从实体框架中动态选择表?
- swift - 迅速和结合。从本地服务恢复一条记录时出现问题