Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
¿Por qué res.json () devuelve nulo?

Estoy tratando de codificar la parte de autenticación de mi aplicación de reacción usando jwt. Seguía recibiendo este error en mi archivo App.js: 'Error de tipo no capturado (en promesa): no se pueden leer las propiedades de nulo (leyendo 'error')', lo que me llevó a descubrir que cuando se accede a una determinada ruta, que debería volver algunos datos sobre el usuario, el cuerpo de la respuesta en realidad está vacío. Estos son algunos fragmentos de mi código, donde creo que podría estar el problema. Cualquier ayuda sería muy apreciada, gracias de antemano! Además, avíseme si debo proporcionar otros fragmentos de código.

Esto es de mi archivo App.js

 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, }); } }); }, []);

Aquí es donde res.json no devuelve nada

 router.get('/auth', validateToken, (req, res) => { res.json(req.user); });

Este es el middleware de validateToken

 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 answers
Answer question

0

Bien, entonces en su función de middleware, en esta línea en particular,

 const validToken = verify(accessToken, "importantsecret"); req.user = validToken; //we can access the username and id if (validToken) { return next(); }

Aquí, está creando una variable constante llamada "validToken" y configurando req.user en ella. Y luego, está verificando si existe, luego ejecuta next(), pero ¿qué pasa si validToken es nulo/indefinido? ¡Next() nunca se ejecuta entonces!

about 4 years ago · Juan Pablo Isaza Report

0

Tal vez sea porque literalmente no devuelves tu respuesta.

Prueba este.

router.get('/auth', validateToken, (req, res) => { return res.json(req.user); });

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!