JWT中间件在Expert Expict ectect之后无法工作

发布于 2025-01-20 02:49:08 字数 1730 浏览 0 评论 0原文

这是我的index.js

import express from "express";
import router from "./routes/routes.js";
import connectDB from "./db.js";

const app = express();

connectDB();

app.use(express.json());

app.use("/", router);

app.listen(3000, () => console.log("server is running on port 3000"));

它在帖子请求上使用中间件功能

import express from "express";
import jwt from "jsonwebtoken";
import authenticateToken from "./middlewares/authenticateToken.js";

const app = express();
app.use(express.json());

app.get("/", (req, res) => res.send("Node and JWT"));

app.post("/login", (req, res) => {
  const user = {
    id: 1,
    username: "JhonDoe",
    email: "[email protected]",
  };

  const token = jwt.sign(user, "secret", { expiresIn: "1day" });
  res.json({ token });
});

app.post("/posts", authenticateToken, (req, res) => {
  const user = req.user;
  res.json(user);
});

app.listen(4000, () => console.log("server is running on port 4000"));

,这是中间件

export default function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  console.log(token);
  if (!token) {
    return res.status(401).json({ msg: "No token, authorization denied" });
  }

  try {
    const user = jwt.verify(token, "secret");
    req.user = user;
    next();
  } catch (err) {
    console.log(token);
    res.status(403).json({ msg: "Token is not valid" });
  }
}

这是我的jwt文件, 返回错误“令牌无效”,但是如果我在同一jwt.js文件中使用的邮政请求下方使用它,它可以完美地工作,它向我显示有效载荷,为什么在导入它时它不起作用?

This is my index.js

import express from "express";
import router from "./routes/routes.js";
import connectDB from "./db.js";

const app = express();

connectDB();

app.use(express.json());

app.use("/", router);

app.listen(3000, () => console.log("server is running on port 3000"));

This is my jwt file which uses a middleware function on posts request

import express from "express";
import jwt from "jsonwebtoken";
import authenticateToken from "./middlewares/authenticateToken.js";

const app = express();
app.use(express.json());

app.get("/", (req, res) => res.send("Node and JWT"));

app.post("/login", (req, res) => {
  const user = {
    id: 1,
    username: "JhonDoe",
    email: "[email protected]",
  };

  const token = jwt.sign(user, "secret", { expiresIn: "1day" });
  res.json({ token });
});

app.post("/posts", authenticateToken, (req, res) => {
  const user = req.user;
  res.json(user);
});

app.listen(4000, () => console.log("server is running on port 4000"));

And this is the middleware

export default function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  console.log(token);
  if (!token) {
    return res.status(401).json({ msg: "No token, authorization denied" });
  }

  try {
    const user = jwt.verify(token, "secret");
    req.user = user;
    next();
  } catch (err) {
    console.log(token);
    res.status(403).json({ msg: "Token is not valid" });
  }
}

But when I import it, it doesn't work correctly if I show the token in the console it shows it correctly but it returns the error "token is not valid" but if I use it below the post request in the same jwt.js file it works perfectly it show me the payload, why doesn't it work when I import it?, thanks.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

池予 2025-01-27 02:49:08

解决方案

而不是

export default function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  if (!token) {
    return res.status(401).json({ msg: "No token, authorization denied" });
  }

  try {
    const user = jwt.verify(token, "secret");
    req.user = user;
    next();
  } catch (err) {
    res.status(403).json({ msg: "Token is not valid" });
  }
}

export default function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  if (!token) {
    return res.status(401).json({ msg: "No token, authorization denied" });
  }

  jwt.verify(token, "secret", (err, user) => {
    if (err) return res.status(403).json({ msg: "Token is not valid" });
    req.user = user;

    next();
  });
}

文档 https:/ /Github.com/Auth0/node-jsonwebtoken#readme

Solution

Instead of

export default function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  if (!token) {
    return res.status(401).json({ msg: "No token, authorization denied" });
  }

  try {
    const user = jwt.verify(token, "secret");
    req.user = user;
    next();
  } catch (err) {
    res.status(403).json({ msg: "Token is not valid" });
  }
}

this

export default function authenticateToken(req, res, next) {
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  if (!token) {
    return res.status(401).json({ msg: "No token, authorization denied" });
  }

  jwt.verify(token, "secret", (err, user) => {
    if (err) return res.status(403).json({ msg: "Token is not valid" });
    req.user = user;

    next();
  });
}

Documentation https://github.com/auth0/node-jsonwebtoken#readme

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文