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

283
Vistas
Cannot GET after middleware using Express and next() function

I'm trying to apply a middleware that modifies the "req" parameter, it works perfectly until I finally use the next() function. This is the code from the middleware:

auth.js

import jwt from "jsonwebtoken";

export const auth = (req, res, next) => {
    try{
        const token = req.header("x-auth-token");
        if(!token) return res.status(401).json({msg: "No authentication token, access denied"});
        const verified = jwt.verify(token, process.env.JWT_SIGNIN_KEY);
        if(!verified) return res.status(401).json({msg: "Token verification failed, authorization denied"});
        req.user = verified._id;
        next();
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
}

This middleware is executed in the users controller, as follows:

userController.js

export const userIndex = asyncHandler(auth, async (req, res) => {
    const user = await User.findById(req.user);
    res.json({
        displayName: user.displayName,
        id: user._id,
    });
})

And after that I associate this function to the user routes:

userRoutes.js

import { googleLogin, tokenIsValid, userIndex } from "../controllers/userController.js";
import express from 'express'
const router = express.Router()

router.route('/getUser').get(userIndex)
router.route('/googlelogin').post(googleLogin)
router.route('/tokenIsValid').post(tokenIsValid)

export default router
import connectDB from './backend/config/db.js'
import userRoutes from './backend/routes/userRoutes.js'
import dotenv  from 'dotenv'
import express from 'express'

connectDB() // Ejecuto la conexión a la base de datos

dotenv.config() // Llamo a las variables de .env

const app = express() // Defino el servidor

app.use(express.json()); // Permite que el servidor entienda los datos enviados en formato JSON
app.use('/api/users', userRoutes) // Creo las rutas para el usuario

const PORT = process.env.PORT || 5000 // Defino un puerto para el servidor

// Ejecuto el servidor
app.listen(PORT, console.log(`La aplicación está corriendo en entorno de ${process.env.NODE_ENV} sobre el puerto ${PORT}`))

The problem occurs when I call this route, it will always return 404 error:

Error Picture

I think that this error is happening bc of the next() function.

Any clue ?

Thanks guys !!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

After checking the package that you are using, it only expects one function as a parameter, but you are passing more than one and this will cause the error. I would change your code in the following way:

userController.js

export const userIndex = asyncHandler(async (req, res) => {
    const user = await User.findById(req.user);
    res.json({
        displayName: user.displayName,
        id: user._id,
    });
})

userRoutes.js

import { googleLogin, tokenIsValid, userIndex } from "../controllers/userController.js";
import express from 'express'
const router = express.Router()

router.get('/getUser', auth, userIndex)
router.post('/googlelogin', googleLogin)
router.post('/tokenIsValid', tokenIsValid)

export default router
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