JWT提供无效令牌

时间:2020-05-24 00:10:23

标签: reactjs typescript jwt

在本地工作,我的jwt令牌无效,但在jwt.io中它显示了已验证的签名。不知道我在想什么。每当我尝试在应用程序中调用api时,签名都会无效。

Link.js

const { Router } = require("express");
const Link = require("../models/Link");
const auth = require("../middleware/auth.middleware");
const router = Router();

router.get("/", auth, async (req, res) => {
try {
const links = await Link.find({ owner: req.user.userId });
res.json(links);
} catch (error) {
res.status(500).json({ message: "Something went wrong, try again" });
}
});

auth.middleware.js

const jwt = require("jsonwebtoken");
const config = require("config");


module.exports = (req, res, next) => {
if (req.method === "OPTIONS") {
return next();
}

try {
const token = req.headers.authorization; // Token

if (!token) {
  return res.status(401).json({ message: "No Authorization" });
}

const decoded = jwt.verify(token, config.get("secret"));

req.user = decoded;
next();
} catch (error) {
res.status(401).json({ message: "No Authorization" });
}
};

Links.tsx

const LinksPage: React.FC = () => {
const [links, setLinks] = useState([]);
const fetchLinks = useCallback(async () => {
try {
  const fetched = await request("http://localhost:5000/api/link/", "GET", null, {
    Authorization: Token,
  });
  setLinks(fetched);
} catch (error) {
  alert(error);
}
}, []);
};

2 个答案:

答案 0 :(得分:0)

也许不是您想要的“ req.headers.authorization ”。 尝试在Chrome,Firefox中使用 console.log(req.headers.authorization) F12。

我建议您也 POSTMAN (免费软件)。它对调试后端(服务器端)很有帮助。

答案 1 :(得分:0)

我解决了这个问题。我必须存储在客户端中的json.parse(token)才能进行jwt.verify(token,secret),但是我正在验证包含令牌和userId对象的字符串。