javascript - 在将标头发送到 ServerResponse.setHeader 的客户端后无法设置标头
问题描述
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 存储库中查看路由和中间件。
解决方案
似乎在使用asyncHandler()
时,当您调用该next
函数时,它会继续执行代码,因此在next()
每个next()
.
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()
return; // here
} catch (error) {
console.log(error)
res.status(401)
throw new Error('Not Authorized, token failed')
}
并且在控制器中也这样做,当您使用res.json
或res.send
使用返回时
return res.json({message: 'message'})
asyncHandler
不会让你return res.json
,所以我认为在下一行添加一个回报是解决它的一种方法。
推荐阅读
- node.js - 如何使异步同步 => 如何测试异步处理(即写入文件)
- mongodb - 如何更新 MongoDB 集合中所有记录的一个日期/时间字段?
- c# - 平均方法首先不起作用的 asp.net 核心代码:
- java - CSS在jsp中不起作用
- azure - 如何使用 Let's Encrypt 为自定义域设置 SSL 生成器
- php - 在会话存储中随机播放项目一次
- react-native - AXIOS 安装问题
- haskell - 给出 Applicative f 时无法推断 (Applicative f0)
- javascript - 视图中的 React-360 相机位置
- php - 如何在 PHP (CSS & Jquery) Video.js WordPress 插件中添加额外链接?