Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
Why is res.json() returning null?

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 };
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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!

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda