Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

After check the package that you are using, it only receives a function as parameter, you are passing more than one and it can originate 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

Finally, if you want to create a project with express and typescript from a template using n-tier architecture, I recommend you this package that I built link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading