I'm following this tutorial: https://www.youtube.com/watch?v=rMiRZ1iRC0A, around 1hr in where i'm developing an 'updating user' request.
However, once I do this, it appears i'm returning an empty JSON {} from my put request. It doesn't appear that I have any issues - I've actually gone straight to copying his github code and yet nothing.
Firstly, I have my verification through jwt, which appears to work. E.g if you pass an incorrect Header param, you will get "You are not authenticated". However - if you use the correct one, {} is returned. See below.
const jwt = require("jsonwebtoken")
const verifyToken = (req, res, next) => {
const authHeader = req.headers.token;
if (authHeader) {
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.JWT_SEC, (err, user) => {
if (err) res.status(403).json("Token is not valid!");
req.user = user;
next();
});
} else {
return res.status(401).json("You are not authenticated!");
}
};
const verifyTokenAndAuthorization = (req, res, next) => {
verifyToken(req, res, () => {
if (req.user.id === req.params.id || req.user.isAdmin) {
next();
} else {
res.status(403).json("You are not alowed to do that!");
}
});
};
module.exports = {verifyToken, verifyTokenAndAuthorization}
Otherwise, this is build into the router.put function within the user file. Please see below.
const { verifyToken, verifyTokenAndAuthorization } = require("./verifyToken");
const router = require("express").Router();
//UPDATE
router.put("/:id", verifyTokenAndAuthorization, async (req, res) => {
if (req.body.password) {
req.body.password = CryptoJS.AES.encrypt(
req.body.password,
process.env.PASS_SEC
).toString();
}
try {
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
res.status(200).json(updatedUser);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
And lastly, this is then called in the index.js, as per the standard app.use functions. I can confirm that my login/register API works, however if I attempt to change/update my user through a token as above, I'm not getting anything back.
E.g I use PUT localhost:5000/api/users/6177ede36c42e26f1d3c7b5f, and it returns {}
Can anyone see what i'm missing here!