Home > OS >  How to properly give next() in the middleware in node app
How to properly give next() in the middleware in node app

Time:01-10

I am trying to verify the bearer token which has been generated after the login request. I have segregated the codes for controllers, middlewares and routes. The login is working fine and is able to generate the token but when I try to verify it I get the following error:

Error: Route.post() requires a callback function but got a [object Undefined]        
    at Route.<computed> [as post] (C:\Users\Desktop\loginapi\node_modules\express\lib\router\route.js:211:15)
    at Function.proto.<computed> [as post] (C:\UsersDesktop\loginapi\    at Module.require (node:internal/modules/cjs/loader:1028:19)
    at require (node:internal/modules/cjs/helpers:102:18)    at Object.<anonymous> (C:\Users\Desktop\loginapi\index.js:15:20)  
[nodemon] app crashed - waiting for file changes before starting...

Below is the complete Code:

Server.js //Main file

const express = require('express')
const app = express()
require('dotenv').config();

const port = process.env.PORT;


console.log(port)

//initialize middleware
app.use(express.json())


//import routes
const authRoutes = require('./src/routes')

// initialize routes
app.use('/abc', authRoutes)

// console.log();

//app start
const appStart = () => {
    try {
        app.listen(port, ()=> {
            console.log(`The app is listening at http://localhost:${port}`)
        })
    } catch (error) {
        console.log(`${error.message}`)
    }
}

appStart()

routes/index/js

const { Router} =  require('express')
const userController = require('../controllers/index')
const { verifyToken } = require('../middlewares/verifyTokens')
const router = Router()


router.post('/login', userController.login)
router.post('/profile',verifyToken ,userController.profile)

module.exports = router

middlewares/verifyTokens.js

// Function to verify whether the bearer token is correct or not
function verifyToken(req, resp, next) {
    const bearerHeader = req.headers['authorization'];
    if (typeof bearerHeader !== 'undefined') {
        const bearer = bearerHeader.split(" ");
        const token = bearer[1];
        req.token = token;
        next();
    } else {
        resp.send({
            result: 'Invalid Token'

        })
    }
}

module.exports = verifyToken

contollers/index.js

const { sign } = require('jsonwebtoken')
const secret = process.env.SECRET;


//login function
const login = async (req, res) => {
  payload = {
    "email": "[email protected]",
    "password": "user123"
  }
  console.log(payload)
  try {
    sign(payload, secret, (err, token) => {
      try {
        res.json({
          token
        })
        // console.log(typeof resp.json)

      } catch (err) {
        res.send(err.message);
      }
    })
  } catch (error) {
    console.log(error.message)
    return res.status(500).json({
      error: error.message
    })
  }
}


const profile = async (req,res) => {
  try {
    return res.status(200).json({
      success: true,
      message: 'In Profile',
    })

  } catch (error) {
    console.log(error.message)
    return res.status(500).json({
      error: error.message
    })
  }
}

const userControllers = {
  login,
  profile
}

module.exports = userControllers

There is some problem with the middleware verifyTokens ,I have gone through other answers but I am not getting it. Can someone please point it out as to where I am going wrong. It will be very helpful. Thank you

CodePudding user response:

Import verifyTokens without { } it will solve the problem.

In routes/index/js :

const verifyTokens = require('../middlewares/verifyTokens')

CodePudding user response:

Instead of this

router.post('/login', userController.login)
router.post('/profile',verifyToken ,userController.profile)

try this one

router.post('/login',(req, res) => {
  userController.login
});

router.post('/profile', 
 (req, res, next) => {
   verifyToken
 }, 
 (req,res,next) => {
   userController.profile
 }
);
  • Related