我的get请求不起作用,但将其更改为post起作用



我有一个get请求,它应该返回他们创建的所有登录用户的项目,我相信代码写得很好。当我在poster上运行它时,我总是会收到401 unauthorised错误,但当我将请求更改为patch时,例如,当我在Poster上运行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返回

您有两个try-catch返回401,但您没有记录错误或将错误返回到前端。您需要在auth中间件和get请求中的2个catch块中添加console.log(e)

try { 
// some of your code 
} catch (e) {
console.log(e); //Add this line 
res.status(401).send({ error: 'Please authenticate' })
}

相关内容

最新更新