Problem authentification bearer with react native

43 Views Asked by At

The connexion is working but when i tried to get information from my DB with the middleware on, i have an error 401. For information, the request works on postman but not on my app.

I think the problem comes from the authentification bearer in my fetch

my middleware :

/* 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!",
    });
  }
};

And my fetch

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);
        },
      );
  };
0

There are 0 best solutions below