首页 > 解决方案 > asyncData 从 db 获取配置文件

问题描述

所以我想使用 asyncdata 和 axios 从 db 获取,这是代码,问题是没有发送请求,我想知道是否有人可以帮助我捕捉错误。

async asyncData({ $axios, store }) {
    try {
      let profile = await $axios.$get('/profile', store.state.auth.id)
      
      return { profile }
    } catch (error) {
      console.log(error.message)
    }
  },
router.get('/profile', async (req, res) => {
  const { userId } = req.body

  try {
    const profileUser = await User.findById(userId)

    res.send(profileUser)
  } catch (e) {
    console.log(e)
    res.status(400).json(e.message)
  }
})

标签: mongodbexpressvue.jsmongoosenuxt.js

解决方案


如果要将 id 作为参数传递,您可能需要将路由修改为以下内容

router.get('/profile/:id', async (req, res) => {
  const { userId } = req.params.id;

  try {
    const profileUser = await User.findById(userId)

    res.send(profileUser)
  } catch (e) {
    console.log(e)
    res.status(400).json(e.message)
  }
})

并将配置文件 ID 添加为路由参数

async asyncData({ $axios, store }) {
    try {
      let profile = await $axios.get('/profile/{profile_id_here}')
      
      return { profile }
    } catch (error) {
      console.log(error.message)
    }
  }

否则,如果您想获取经过身份验证的用户的 id(可以从 Bearer 令牌解析),则需要将其设置为request身份验证中间件中的对象。

在您的身份验证中间件中,

const user = await _authService.validateFromToken(bearerToken);
 if (user) {
      req.user = user;
  }

然后您可以访问经过身份验证的用户,

router.get('/profile', async (req, res) => {
  const { userId } = req.user._id;

  try {
    const profileUser = await User.findById(userId)

    res.send(profileUser)
  } catch (e) {
    console.log(e)
    res.status(400).json(e.message)
  }
})

推荐阅读