首页 > 解决方案 > 在将标头发送到 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 存储库中查看路由和中间件。

标签: javascriptnode.jsexpressjwtexpress-jwt

解决方案


似乎在使用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.jsonres.send使用返回时

return res.json({message: 'message'})

asyncHandler不会让你return res.json,所以我认为在下一行添加一个回报是解决它的一种方法。


推荐阅读