在Multer和JWT上遇到麻烦

发布于 2025-01-24 15:18:45 字数 1132 浏览 2 评论 0原文

我目前正在尝试将自己的头缠住:

基本上,我正在尝试在用multer上传文件之前验证用户令牌。 问题是cookie的JWT是“未定义的”。

这是路线片段:

router.post("/files/user/:userId", verifyJWT, upload.single("file"), controllerFunction);

在我的验证方法中,我正在做:

exports.verifyJWT = async (req, res, next) => {
  let accesToken = req.cookies.jwt;

  if (!accesToken) {
    return res.status(401).json({
      message: "Acces is unauthorized.",
    });
  }

  let payload;

  try {
    payload = jwt.verify(accesToken, process.env.JWT_KEY);
    req.name = payload.name;
    req.type = payload.type;
    req._id = payload._id;
    next();
  } catch (err) {
    res.status(403).json({ message: "Token could not be verified!" });
  }
};

如果我的路线具有 verifyjwt middleware ,无论我称呼 console.log(accestoken), acces令牌被发送为未定义。

如果我从“/files/user/:userId”路由中删除了中间件验证,以及 console.log(accestoken)我将接收令牌。

这仅发生在包含Multer上传回调的路线上。

我已经尝试了此线程的建议原因似乎不起作用

I'm currently trying to wrap my head around this:

Basically I am trying to verify the users token before uploading the file with multer.
The problem is the JWT from the cookie is "undefined".

This is the route snippet:

router.post("/files/user/:userId", verifyJWT, upload.single("file"), controllerFunction);

In my verifyJWT method I'm doing:

exports.verifyJWT = async (req, res, next) => {
  let accesToken = req.cookies.jwt;

  if (!accesToken) {
    return res.status(401).json({
      message: "Acces is unauthorized.",
    });
  }

  let payload;

  try {
    payload = jwt.verify(accesToken, process.env.JWT_KEY);
    req.name = payload.name;
    req.type = payload.type;
    req._id = payload._id;
    next();
  } catch (err) {
    res.status(403).json({ message: "Token could not be verified!" });
  }
};

If my route has the verifyJWT middleware for whatever reason when I'm calling console.log(accesToken) the acces token is sent as undefined.

If i remove the middleware verifyJWT from the "/files/user/:userId" route, and console.log(accesToken) I'm receiving the token.

This only happens on the route which has the multer upload callback in it.

I have already tried the suggestions from this thread but for whatever reason it does not seem to work

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文