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

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

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 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!