在帖子中显示评论可以通过使用Node.js、Express和MongoDB来实现。以下是一个基本的实现过程:
npm init -y
npm install express mongoose body-parser
app.js
(或者任何你想要的名称)的主文件,并在其中导入所需的模块:const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/comments', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Failed to connect to MongoDB', err));
这将连接到名为"comments"的本地MongoDB数据库。确保MongoDB已在本地运行。
const commentSchema = new mongoose.Schema({
text: String,
author: String
});
const Comment = mongoose.model('Comment', commentSchema);
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/comments', (req, res) => {
Comment.find({}, (err, comments) => {
if (err) {
res.status(500).send(err);
} else {
res.json(comments);
}
});
});
这将返回所有评论的JSON数组。
app.post('/comments', (req, res) => {
const { text, author } = req.body;
const newComment = new Comment({ text, author });
newComment.save((err, comment) => {
if (err) {
res.status(500).send(err);
} else {
res.json(comment);
}
});
});
这将接收来自请求体的评论文本和作者信息,并将其保存到数据库中。
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
node app.js
现在,你的服务器将在本地的端口3000上运行。你可以使用Postman或类似的工具向http://localhost:3000/comments
发送GET和POST请求来获取和创建评论。
请注意,这只是一个基本的实现示例,你可以根据需求进行更多的定制和优化。如果需要更复杂的功能,你可能需要添加身份验证、分页、编辑和删除评论等功能。
对于腾讯云相关产品,可以使用腾讯云云服务器(Elastic Cloud Server)来托管Node.js应用,并使用腾讯云数据库MongoDB版来存储评论数据。有关产品的更多详细信息,请查看以下链接:
领取专属 10元无门槛券
手把手带您无忧上云