问题描述
Github:https://github.com/UJJWAL2001/Pro-Shop/tree/main/backend
我正在尝试使用 JWT 令牌通过下面给出的中间件来保护我的路由
import jwt from 'jsonwebtoken'
import User from '../models/userModel.js'
import asyncHandler from 'express-async-handler'
const protect = asyncHandler(async (req,res,next) => {
let token
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
try {
token = req.headers.authorization.split(' ')[1]
const decoded = jwt.verify(token,process.env.JWT_SECRET)
req.user = await User.findById(decoded.id).select('-password')
console.log(req.user)
next()
} catch (error) {
console.log(error)
res.status(401)
throw new Error('Not Authorized,token failed')
}
}
if (!token) {
res.status(401)
throw new Error('Not authorized,no token found')
}
next()
})
export { protect }
我走正确的路线,但仍然收到这个
{
"message": "Not found - /api/users/profile","stack": "Error: Not found - /api/users/profile\n at notFound (file:///Users/ujjwalchaudhary/Desktop/proshop/backend/middleware/errorMiddleware.js:2:17)\n at Layer.handle [as handle_request] (/Users/ujjwalchaudhary/Desktop/proshop/node_modules/express/lib/router/layer.js:95:5)\n at trim_prefix (/Users/ujjwalchaudhary/Desktop/proshop/node_modules/express/lib/router/index.js:317:13)\n at /Users/ujjwalchaudhary/Desktop/proshop/node_modules/express/lib/router/index.js:284:7\n at Function.process_params (/Users/ujjwalchaudhary/Desktop/proshop/node_modules/express/lib/router/index.js:335:12)\n at Immediate.next (/Users/ujjwalchaudhary/Desktop/proshop/node_modules/express/lib/router/index.js:275:10)\n at Immediate._onImmediate (/Users/ujjwalchaudhary/Desktop/proshop/node_modules/express/lib/router/index.js:635:15)\n at processImmediate (internal/timers.js:464:21)"
}
我检查过我正在点击 api/users/profile -> protect
-> getUserProfile
->app.use(notFound)
->app.use(errorHandler)
但是循环应该在 res.json({...})
的 getUserProfile
你可以在上面提到的我的 github repo 中查看路由和中间件。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)