Javascript 在后端使用节点js尝试配置文件路由,而不使用passport.js进行身份验证
我正在尝试在我的项目中为用户创建配置文件页面,而不使用passaport.js进行身份验证。 我创建了一个用于AustNotification的中间件,它是check-auth.js。我正在使用失眠来访问我的个人资料路由令牌。我从check-auth.js中得到错误。有人能帮我解决这个问题吗? 谢谢Javascript 在后端使用节点js尝试配置文件路由,而不使用passport.js进行身份验证,javascript,node.js,express,authentication,Javascript,Node.js,Express,Authentication,我正在尝试在我的项目中为用户创建配置文件页面,而不使用passaport.js进行身份验证。 我创建了一个用于AustNotification的中间件,它是check-auth.js。我正在使用失眠来访问我的个人资料路由令牌。我从check-auth.js中得到错误。有人能帮我解决这个问题吗? 谢谢 这是用于身份验证的中间件(检查auth.js) 2-这是我个人资料页面的用户控制器。(users.js) 3-这是用户的我的路线(用户路线) 我找到了解决办法。它需要是``req.userData=
我找到了解决办法。它需要是``req.userData=decodedToken`,而不是``req.userData={userId:decodedToken.userId}`。它起作用了
const jwt = require('jsonwebtoken')
const HttpError = require('../models/HttpError')
module.exports = (req, res , next) => {
if(req.method === 'OPTIONS'){
return next()
}
try {
const token = req.headers.authorization.split(' ')[1] //We took token from headers authorization.( Bearer 'token')
if(!token){ // We check token if it is falsy.If it is, We will send error for authentication failed
throw new Error('Authentication failed')
}
const decodeToken = jwt.verify(token,process.env.JWT_SECRET_KEY) // for verifying token we need token and our secret key.
console.log(decodeToken.userId)
console.log(req.isLoggedIn)
req.userData = {userId:decodedToken.userId} // We will use userid to delete and edit recipes and meals. we need that.
next() // It is authenticated go next middleware
}
catch(err){ // if our token does not match with the token.
const error = new HttpError('Authentication failed mi', 403)
return next(error) // Send error
}
}
const profile = async(req, res, next) => {
let existingUser
try{
existingUser = await User.findById(req.userData.userId,'-password').exec()
}
catch(err){
const error = new HttpError('Profile failed, please try again', 500)
return next(error)
}
if(!existingUser){
const error = new HttpError('User does not exist',422)
}
res.status(200).json({user:existingUser.toObject({getters:true})})
}
const express = require('express')
const {check} = require('express-validator')
const router = express.Router()
const usersController = require('../controllers/users')
const checkAuth = require('../middleware/check-auth')
router.post('/signUp', [
check('username').not().isEmpty(),
check('age').not().isEmpty(),
check('gender').not().isEmpty(),
check('email').normalizeEmail().isEmail(),
check('password').isLength({min:6})
],usersController.signUp)
router.post('/login',[
check('email').normalizeEmail().isEmail(),
check('password').isLength({min:6})
],usersController.login)
router.use(checkAuth)
router.get('/profile',usersController.profile)
module.exports = router