0

I've been stuck on this for a while. So I have an API with express and I'm using Axios to make the request. My problem is that I don't know how can I retreive the user Id from the front end to check if it matches to the userId in the payload of my token. And the weird thing is that I have those other functions right after this auth middleware and I can get the req.body.userId just fine ! I'm so confused.

Since bodyParser is deprecated I'm using this in my configuration :

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

here is my request in the frontend (REACT)

 const fetchPosts = useCallback(() => {
         const formData = new FormData();
         formData.append("userId", userId) 

        Axios.get('http://localhost:3001/api/post', formData,
            {
                headers: {
                    "Authorization": LStoken,
                    "Content-Type": "application/json"
                }
            })
            .then((response) => {
                console.log(response)
                setPosts(response.data)
            })
    }, [LStoken, posts, userId])

and here is my middleware in which I can't retreive the userId from the front

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
    const userId = decodedToken.userId;
    const moderator = decodedToken.moderator
    console.log(moderator)
    console.log(req.body.userId)
    if (req.body.userId && req.body.userId !== userId || req.body.moderator == false ) {
      throw 'Invalid user ID';
    } else {
      next();
    }
  } catch {
    res.status(401).json({
      error: new Error('Invalid request!')
    });
  }
};
A.Tshi
  • 1
  • 2
  • 1
    You're putting the user id into `FormData`, so you need to parse that on your server. This might be helpful: https://stackoverflow.com/questions/56758241/node-js-express-how-to-get-data-from-body-form-data-in-post-request – tromgy Oct 27 '21 at 23:58
  • 0 Hi thank you for answering, I tried to do it with the method in the link but it's not working. Actually it doesn't have to be a formData I just want to get the id of the user in the auth middleware but I don't know if it is because the express parser doesn't work or something else – A.Tshi Oct 28 '21 at 00:43

0 Answers0