node.js - 我的获取请求不起作用,但将其更改为帖子有效
问题描述
我有一个get
请求应该返回他们创建的所有登录用户的项目,我相信代码写得很好。当我在邮递员上运行它时,我总是收到一个401 unauthorised
错误,但是当我将请求更改为补丁时,并且我也在patch
邮递员上运行了一个请求,它可以正常工作。可能是什么问题?
// get all logged in user's projects
router.get('/api/project/mine', auth, async (req, res) => {
try {
const id = req.user._id
const projects = await Project.find({owner: id})
res.status(200).send(projects)
} catch (e) {
res.status(401).send()
}
})
身份验证中间件
const jwt = require('jsonwebtoken')
const User = require('../models/user')
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer ', '')
const decoded = jwt.verify(token, 'creativetoken')
const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })
if (!user) {
throw new Error()
}
req.token = token
req.user = user
next()
} catch (e) {
res.status(401).send({ error: 'Please authenticate' })
}
}
module.exports = auth
注意:auth
确保登录用户的objectId通过返回req.user.id
解决方案
您有 2 个返回 401 的 try-catch,但您没有记录错误或将错误返回到前端。您需要在中间件和请求中添加console.log(e)
2 个 catch 块。auth
get
try {
// some of your code
} catch (e) {
console.log(e); //Add this line
res.status(401).send({ error: 'Please authenticate' })
}
推荐阅读
- .net - 我可以使用一些解决方法来避免混合内容错误吗?
- algorithm - 使用 BFS 算法找到 2 个顶点之间的最短路径
- python - 我想在列表中找到对象的下一个实例,并返回它的索引值
- r - 用R中正确拼写的单词替换拼写错误的单词的功能?
- c - C: -O3 的奇怪标签行为?
- regex - Google 电子表格 RE2 / RegEx - 返回字符串中的所有字母单词
- xaml - WinUI UWP - 如何创建继承自它的自定义样式?
- r - 从R中的长字符串中提取数据
- javascript - 检查 js 数组中是否存在 obj
- python - 我有 2 行名称相同但列中的值不同。我想知道如何使用列值删除其中一行