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!')
});
}
};