首页 > 解决方案 > React - 使用 await fetch 处理 jwt 身份验证失败

问题描述

我编写了一个 API 来做一些事情,并使用jwt令牌保护它。这是检查有效性(checkAuth)的功能:

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization;
    const decoded = jwt.verify(token, process.env.TOKEN_SECRET);
    req.userData = decoded;
    next();
  }
  catch (error) {
    return res.status(401).json({
      message: 'Auth failed'
    });
  }
};

我以这种方式定义routeof :API

router.post('/myAPI', checkAuth, MyAPIDefinition);

当我尝试获取 API 时,使用过期 jwt的我无法获得checkAuth. 这是我API使用的电话await fetch

const response = await fetch(`${API_URI_DEV}/myAPI`, {
  method: 'POST',
  body: JSON.stringify({encod: { content: data }}),
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    Accept: 'application/json',
    'authorization': jwt
  }
});

的内容responseundefined

标签: node.jsreactjsjwtfetch-api

解决方案


推荐阅读