首页 > 解决方案 > 我的获取请求不起作用,但将其更改为帖子有效

问题描述

我有一个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

标签: node.jsmongoose

解决方案


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

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

推荐阅读