mongodb - 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)
}
})
解决方案
如果要将 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)
}
})
推荐阅读
- python - 如何重塑 3D 数组
- vue.js - 如何简化自定义多复选框组件
- java - Java 8 中用户定义对象的默认值
- ssis - 在 ssis 的 DB2 查询中加载日期参数时出现问题
- jquery - 当嵌入式表单提示输入时,jQuery下拉菜单消失
- c - (Enum) -1 在 C 中代表什么值?如何用 Swift 编写它?
- c++ - 如果作业在附加之前完成,QFutureWatcher 的 finished() 信号会被触发吗?
- amazon-web-services - 是否可以在 AWS Data Pipeline 的另一个参数中使用一个参数?
- subquery - WikiData SPARQL 因子查询 + 标签服务 + 可选而超时
- c# - Asp.Net Core - 在共享主机环境中启用 HttpCompression?