I'm trying to code the authentification part of my react app using jwt. I kept getting this error in my App.js file: 'Uncaught (in promise) TypeError: Cannot read properties of null (reading 'error')', which led me to find out that when a certain route is accessed, which should return some data about the user, the response body is actually empty. These are some snippets of my code, where I think the problem might be. Any help would be much appreciated, thanks in advance! Also, please let me know if I should provide other snippets of code
This is from my App.js file
const [authState, setAuthState] = useState({
username: "",
id: 0,
status: false,
});
useEffect(() => {
axios
.get("http://localhost:3001/users/auth", {
headers: {
accessToken: localStorage.getItem("accessToken"),
},
})
.then((response) => {
if (response.data.error) { //this is where the error appears
setAuthState({ ...authState, status: false });
} else {
setAuthState({
username: response.data.username, //if I comment the line where the error appears, I get the same error here and on the line below, but with 'username' and 'id' instead of 'error'
id: response.data.id,
status: true,
});
}
});
}, []);
This is where res.json doesn't return anything
router.get('/auth', validateToken, (req, res) => {
res.json(req.user);
});
This is the validateToken middleware
const { verify } = require('jsonwebtoken');
const validateToken = (req, res, next) => {
const accessToken = req.header("accessToken");
if (!accessToken) return res.json({ error: "User not logged in!" })
try {
const validToken = verify(accessToken, "importantsecret");
req.user = validToken; //we can access the username and id
if (validToken) {
return next();
}
} catch (err) {
return res.json({ error: err });
}
};
module.exports = { validateToken };
CodePudding user response:
Okay, so in your middleware function, in this particular line,
const validToken = verify(accessToken, "importantsecret");
req.user = validToken; //we can access the username and id
if (validToken) {
return next();
}
Here, you are creating a constant variable named "validToken" and setting req.user to it. And then, you are checking if it exists, then run next(), but what if validToken is null/undefined? next() is never ran then!
CodePudding user response:
Maybe it's because you literally don't return your response.
Try this one.
router.get('/auth', validateToken, (req, res) => { return res.json(req.user); });