如何在Node应用程序的中间件中正确使用next()函数。

huangapple go评论84阅读模式
英文:

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

问题

我正在尝试验证在登录请求之后生成的令牌。我已将控制器、中间件和路由的代码分离。

登录功能正常运行,并能够生成令牌,但当我尝试验证它时,我收到以下错误:

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:\Users\Desktop\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...

以下是完整的代码:

Server.js //主文件

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)

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

controllers/index.js

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

// 登录功能
const login = async (req, res) => {
  payload = {
    "email": "abc@gmail.com",
    "password": "user123"
  }
  console.log(payload)
  try {
    sign(payload, secret, (err, token) => {
      try {
        res.json({
          token
        })
      } 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

中间件 verifyTokens 存在问题,我已经查看了其他答案,但我不明白问题出在哪里。有人能指出我哪里错了吗?这将非常有帮助。谢谢。

英文:

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.&lt;computed&gt; [as post] (C:\Users\Desktop\loginapi\node_modules\express\lib\router\route.js:211:15)
    at Function.proto.&lt;computed&gt; [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.&lt;anonymous&gt; (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(&#39;express&#39;)
const app = express()
require(&#39;dotenv&#39;).config();

const port = process.env.PORT;


console.log(port)

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


//import routes
const authRoutes = require(&#39;./src/routes&#39;)

// initialize routes
app.use(&#39;/abc&#39;, authRoutes)

// console.log();

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

appStart()

routes/index/js

const { Router} =  require(&#39;express&#39;)
const userController = require(&#39;../controllers/index&#39;)
const { verifyToken } = require(&#39;../middlewares/verifyTokens&#39;)
const router = Router()


router.post(&#39;/login&#39;, userController.login)
router.post(&#39;/profile&#39;,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[&#39;authorization&#39;];
    if (typeof bearerHeader !== &#39;undefined&#39;) {
        const bearer = bearerHeader.split(&quot; &quot;);
        const token = bearer[1];
        req.token = token;
        next();
    } else {
        resp.send({
            result: &#39;Invalid Token&#39;

        })
    }
}

module.exports = verifyToken

contollers/index.js

const { sign } = require(&#39;jsonwebtoken&#39;)
const secret = process.env.SECRET;


//login function
const login = async (req, res) =&gt; {
  payload = {
    &quot;email&quot;: &quot;abc@gmail.com&quot;,
    &quot;password&quot;: &quot;user123&quot;
  }
  console.log(payload)
  try {
    sign(payload, secret, (err, token) =&gt; {
      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) =&gt; {
  try {
    return res.status(200).json({
      success: true,
      message: &#39;In Profile&#39;,
    })

  } 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

答案1

得分: 0

请尝试以下方式,而不是原来的方式:

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

router.post('/profile',
  (req, res, next) => {
    verifyToken
  },
  (req, res, next) => {
    userController.profile
  }
);
英文:

Instead of this

router.post(&#39;/login&#39;, userController.login)
router.post(&#39;/profile&#39;,verifyToken ,userController.profile)

try this one

router.post(&#39;/login&#39;,(req, res) =&gt; {
  userController.login
});

router.post(&#39;/profile&#39;, 
 (req, res, next) =&gt; {
   verifyToken
 }, 
 (req,res,next) =&gt; {
   userController.profile
 }
);

答案2

得分: 0

导入 verifyTokens 而不需要使用 {} 将解决这个问题。

routes/index/js 中:

const verifyTokens = require('../middlewares/verifyTokens')
英文:

Import verifyTokens without { } it will solve the problem.

In routes/index/js :

const verifyTokens = require(&#39;../middlewares/verifyTokens&#39;)

huangapple
  • 本文由 发表于 2023年1月10日 18:33:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75068687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定