首页 > 解决方案 > 使用 vue js 和 axios 按 id 显示单个记录

问题描述

我有一个 mongodb express vue js 应用程序,它显示卡片中的项目列表,这些项目是指向每条记录的详细视图的链接。如果我将鼠标悬停在卡片上,则会显示链接的正确 ID,但单击任何卡片,它会转到 mongo 的第一个文档,并且不显示记录。视图检索一个项目,但始终是第一个。

如何显示点击项目ID的记录?

报告.vue

在邮递员中工作的后端请求是

// Get Simgle Report
router.get('/:id', async (req, res) => {
  const reports = await loadReportsCollection()
  await reports.findOne({_id: new mongodb.ObjectID( req.params.id)})
  res.send(await reports.find({}).limit(1).toArray())
  res.status(200).send()
  }
)

ReportService.js 看起来像

    //Find Single Report
  static getReport(id) {
    return axios.get(`${url}${id}`)
  }

Report.vue 文件看起来像

mounted () {
    this.getReport()
  },

  methods: {
    async getReport() {
        try {
          const response = await ReportService.getReport(this.$route.params.id)
          this.report = response.data
        } catch(err) {
          this.err = err.message
        }
      },
  }

非常感谢您的帮助!

标签: mongodbexpressvue.js

解决方案


看起来您正在尝试访问您的 api 中的参数而不在您的请求中传递一个参数。你在这里要求参数:

await reports.findOne({_id: new mongodb.ObjectID( req.params.id)})

但您的请求中没有通过任何内容。这应该这样做:

return axios.get('/:id', {
  params: {
    id: `${id}`
  }
})

推荐阅读