【问题标题】:Getting req.user.following undefined获取 req.user.following 未定义
【发布时间】:2020-07-16 22:08:18
【问题描述】:

我正在使用 MERN 创建社交网络应用。我已经实现了关注者和关注,现在我正在尝试获取我关注的唯一用户的帖子列表。所以,如果我 console.log 我的 req.user 我只会得到“id”和“iat”,但我需要更多用户信息,例如以下数组。

这是我所拥有的: auth.js 中间件:

const config = require('config')
const jwt = require('jsonwebtoken')

function auth(req, res, next) {
    const token = req.header('x-auth-token')

    // check for token
    if (!token) return res.status(401).json({ msg: 'Unauthorized token' })

    try {
        // verify token
        const decoded = jwt.verify(token, config.get('jwtSecret'))

        // add user from payload
        req.user = decoded
        console.log('---',decoded)
        next()
    } catch (e) {
        return res.status(400).json({ msg: 'Token is not valid' })
    }
}

module.exports = auth

auth.js

const express = require('express')
const router = express.Router()

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('config')

const User = require('../models/User')
const auth = require('../middleware/auth')

// @route   POST /api/auth
// @desc    Login user
// @access  Public

router.post('/', (req, res) => {

    const { email, password } = req.body

    // filed validation
    if (!email || !password) res.status(400).json({ msg: 'Fields cannot be empty.' })

    // Check if user is registered
    User
        .findOne({ email })
        .then(user => {
            if (!user) res.status(400).json({ msg: `User doesn't exist.` })
            //console.log(user)
            // validate password
            bcrypt
                .compare(password, user.password)
                .then(isMatch => {
                    if (!isMatch) return res.status(400).json({ msg: 'Invalid password' })

                    // if password matches, send token and user
                    jwt.sign(
                        { id: user.id },
                        config.get('jwtSecret'),
                        (err, token) => {
                            if (err) throw err

                            res.json({
                                token,
                                user: {
                                    id: user.id,
                                    email: user.email,
                                    first_name: user.first_name,
                                    last_name: user.last_name,
                                    registration_date: user.registration_date,
                                    profile_image: user.profile_image,
                                    user_bio: user. user_bio,
                                    followers: user.followers,
                                    following: user.following
                                }
                            })
                        }
                    )
                })
        })

})

这是我的控制台日志

 Server started at port 5000
[0] --- { id: '5efccfb13224e1489439bcfd', iat: 1593626545 }
[0] * { id: '5efccfb13224e1489439bcfd', iat: 1593626545 }

编辑:

// @route   GET /api/posts/subscribedPost
// @desc    get all subscribed post
// @access  Private

router.get('/subscribedPost', auth, (req, res) => {
    console.log('*',req.user)     // not working correctly, have only id and iat
    Post
        .find({userID: req.user.id})
        .populate('userID', 'first_name last_name profile_image _id')
        .sort({ registration_date: -1 })
        .then(post => res.json(post))
        .catch(err => res.json(err))
    
})

【问题讨论】:

    标签: node.js reactjs express mern


    【解决方案1】:

    这是因为您仅使用 id 签署您的 JWT 令牌,因此当您对其进行解码时,您只会得到 id

    jwt.sign({ id: user.id },config.get('jwtSecret'),(err, token) =>{})
    

    这里你只是传递id,你可以传递你的整个user对象来获取所有数据

    jwt.sign(user.toJSON(),config.get('jwtSecret'),(err, token) =>{})
    

    PS- 你可能不想通过你的全部USER,只是为了演示

    您可以自定义您想要的值。

    【讨论】:

    • 是的,但现在我只有在用户登录时才能得到正确的结果,但我随时需要
    • 我不知道你是什么意思?你能详细说明一下吗
    • 如果我登录,我会得到整个用户的正确响应,并且我可以访问例如 req.user.following 这很好,但如果我提出其他请求,例如 @987654328 @ 如果我控制台日志 req.user 我只得到它的 'id' 和 'iat'
    • 我进行了编辑,这样您就可以看到我试图获得整个用户的路线,而不仅仅是 id
    • 好的,我现在得到了一些东西,但它只有在用户登录时才有效,例如:用户开始关注另一个用户,他应该看到它的帖子,但他没有,他只有在他再次登录,并且刷新了数据,如何解决这个问题?
    【解决方案2】:

    您需要在auth中间件中获取用户数据DB,然后将其添加到req.user中。因此,如果用户有任何更改,您将获得更新的用户数据。

    例如:

    function auth(req, res, next) {
        const token = req.header('x-auth-token')
    
        // check for token
        if (!token) return res.status(401).json({ msg: 'Unauthorized token' })
    
        try {
            // verify token
            const decoded = jwt.verify(token, config.get('jwtSecret'))
    
            // get the user from DB
    
            const user = User.findById(decoded.id) //only populate fields which are required
    
            req.user = user
            console.log('---',decoded)
            next()
        } catch (e) {
            return res.status(400).json({ msg: 'Token is not valid' })
        }
    }
    

    【讨论】:

    • 我的 console.log(req.user.following) 仍然未定义,为什么?
    • 和 console.log(req.user) 给我 Post 而不是 User 架构
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2016-07-31
    • 2019-02-10
    相关资源
    最近更新 更多