首页 > 解决方案 > 具有本机反应的问题身份验证承载

问题描述

连接正在工作,但是当我尝试在中间件打开的情况下从我的数据库中获取信息时,出现错误 401。有关信息,该请求适用于邮递员,但不适用于我的应用程序。

我认为问题来自我获取的身份验证承载

我的中间件:

/* Middleware */
const authentification = (req, res, next) => {
  try {
    /* decode token and compare, set userID */
    const token = req.headers.authorization.split(" ")[1];
    const decodedToken = jwt.verify(token, "RANDOM_TOKEN_SECRET");
    const userId = decodedToken.userId;

    /* if userID in body compare with DB userID, else (no userID in body) it's ok*/

    if (req.body.userId && req.body.userId !== userId) {
      throw "Invalid user ID";
    } else {
      User.findOne({ _id: userId }, (err, data) => {
        if (err) {
          res.status(500).json({
            error: new Error("Internal server error"),
          });
          return;
        }

        if (!data) {
          res.status(404).json({
            message: "Erreur d'authentification",
          });
          return;
        }

        req.user = data;
        next();
      });
    }
  } catch {
    res.status(401).json({
      message: "Invalid request!",
    });
  }
};

还有我的

getClubUser = async () => {
    const headers = new Headers({
      'Content-type': 'application/json',
      Authorization: 'bearer' + (await AsyncStorage.getItem('token')),
    });
    const options = {
      method: 'GET',
      headers: headers,
    };

    fetch('http://localhost:8080/dashboard/clubInfo', options)
      .then((response) => {
        console.log(response);
        return response.json();
      })
      .then(
        (data) => {
          this.setState({sport: data});
          console.log(this.state.sport.clubs);
        },

        (err) => {
          console.log(err);
        },
      );
  };

标签: javascriptreact-nativeconnexion

解决方案


推荐阅读