【问题标题】:postman when testing GET it returns 200 but with an empty body邮递员在测试 GET 时返回 200 但正文为空
【发布时间】:2021-10-16 08:25:37
【问题描述】:

当我尝试使用邮递员测试我的 GET API 时,它返回 200 但正文为空,我期望获得的数据不会显示。

找到我的 server.js 文件和 POSTMAN 结果的截图

app.get('/api/articles/:name', async (req, res) => {

    try {
        const articleName = req.params.name;

        const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
        const db = client.db('my-blog');

        const articleInfo = await db.collection('articles').findOne({ name: articleName })
        res.status(200).json(articleInfo)

        client.close()
    }
    catch (error) {
        res.status(500).json({ message: 'error connecting to db', error })
    }

})

【问题讨论】:

  • 您检查过代码中articleInfo 的值吗?您可以输入console.log 或在调试模式下运行应用程序。
  • 是的,我得到“未定义”仍在尝试解决它,我怀疑我的数据库连接,因为数据通常来自数据库。
  • 我在我的机器上查看了你的代码,它运行良好,检查你的收藏名称是否以's'结尾 例如:文章不是文章
  • 所以,您的代码没有任何问题。我相信两种情况是可能的,数据库连接有问题(检查参数)或数据库与给定的文章名称不匹配
  • @PrakashBhosale Ohkay,我的收藏名称是正确的谢谢。

标签: node.js api express get postman


【解决方案1】:

在这里,我已将您的代码更新如下,请将您的 server.js 移出 /src 文件夹。它现在可以工作了。

const express = require('express')
const bodyParser = require('body-parser')
const {MongoClient} = require("mongodb");
const url = 'mongodb://127.0.0.1:27017';
const app = express();
app.use(bodyParser.json());
app.get('/api/articles/:name', async (req, res) => {
    try {
        const articleName = req.params.name;
        MongoClient.connect(url, async (err, db) => {
            const client = db.db('article');
            const articleInfo = await client.collection('articles').findOne({title: articleName})
            res.send(articleInfo)
        });

    } catch (error) {
        res.status(500).json({ message: 'Error connecting to db', error });
    }

});
app.listen(8000, () => console.log('Listening on port 8000'));

【讨论】:

  • 如果它是一个解决方案,请投票给一个有用的答案。提前谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2019-12-16
相关资源
最近更新 更多