如何访问受保护的身份验证路由节点/ JWT

时间:2019-10-18 16:43:59

标签: node.js api authentication jwt backend

我很拼命,坚持了好几天...我是Node / JWT的新手,我似乎找不到适合我需要的任何指南,如果我解决这个问题,我很乐意支付问题。

我正在尝试访问受保护的路由“ / users / me”,如下所示:

Router

在GET请求上,身份验证中间件将触发,并且看起来像这样:

const jwt = require('jsonwebtoken')
const User = require('../models/userModel')

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, 'secretWasUsed')
        const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })

        if (!user) throw new Error()

        req.token = token
        req.user = user
        next()
    } catch (error) {
        res.status(401).send({
            error: 'Please authenticate ' + error,
        })
    }
}

module.exports = auth

WebController.getMe返回res.json(req.token)

前端代码

document.querySelector('#myProfile').addEventListener('click', () => {
    http.getAuth('/users/me')
})

GET AUTH is defined in the other class (its imported on the top)


getAuth(url) {
        fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': window.localStorage.getItem('token')
            }
        }).then(response => {
            if (response.status === 200) {
                return response.json()
            } else {
                throw new Error('There was an error in Authentication!')
            }
        }).then(json => {
            return console.log(json)
        })
        .catch(err => console.log(err))
}

目标:传递身份验证中间件并重定向到/ users / me 现实:我没有通过身份验证中间件,但得到了令牌。 GITHUB:https://github.com/Elvis339/ActiveCollab-Superhero

最好下载项目,并通过邮递员在此URL http://localhost:3000/上创建用户

{
    "name": "test",
    "email": "test@gmail.com",
    "password": "test"
}

登录>我的个人资料(这就是发生问题的地方)

0 个答案:

没有答案