我真的是一个新的行业和有这个错误时,试图检查数据库连接通过API的请求与 Postman .....请帮助我解决这个问题...
我只是想通过发送API请求来检查mongodb数据库。但我仍然无法识别错误,我正在遵循一套教程,并发生了这个问题...任何人都可以帮助我识别错误,这是非常感谢....
{这是虚拟文本,请添加更多详细信息...
这是我的代码...
const app = express();
const { MongoClient } = require('mongodb');
const PORT = process.env.PORT || 8000;
// Initialize middleware
// we used to install body parser but now it's a built in middleware
// Function of express. It parses incoming JSONpayload
// app.use(express.json({extended:false}));
app.use(express.json({ extended: false }));
// Test Routs
// app.get("/", (req,res)=>res.send("Hello Aruna !!!"));
// app.post("/", (req,res)=>res.send(`Hello ${req.body.name} `));
// app.get("/hello/:name", (req.res)=>res.send(`Hello ${req.params.name}`))
app.get('/api/articles/:name', async (req, res) => {
try {
const articleName = req.params.name;
const client = await MongoClient.connect('mongodb://localhost:27017');
const db = client.db('mernblog');
const articlesinfo = db
.collection('articles')
.findOne({ name: articleName });
res.status(200).jason(articlesinfo);
client.close();
} catch (error) {
res.status(500).jason({ message: 'Error connecting to database', error });
}
});
app.post('/api/articles/:name/add-comments', (req, res) => {
const { username, text } = req.body;
const articleName = req.params.name;
articlesinfo[articleName].comments.push({ username, text });
res.status(200).send(articlesinfo[articleName]);
});
app.post('/', (req, res) => res.send(`Hello ${req.body.name}`));
app.get('/hello/:name', (req, res) => res.send(`Hello ${req.params.name}`));
app.listen(PORT, () => console.log(`Server is running at port ${PORT}`));
1条答案
按热度按时间olmpazwi1#
您的代码中有一个打字错误:
jason
应该是json
。其他提示,你应该在一个单独的方法中处理你的DB连接,并更改你的
post
请求,因为articlesinfo
不是一个全局变量: