英文:
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.<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": "abc@gmail.com",
"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
答案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('/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
}
);
答案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('../middlewares/verifyTokens')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论