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:
I think that this error is happening bc of the next() function.
Any clue ?
Thanks guys !!