[英]Why can't I use middleware in my express route?
I am creating an API, so I want to add a user system and validate access to the API.我正在创建一个 API,所以我想添加一个用户系统并验证对 API 的访问。
This would be the middleware for validation:这将是用于验证的中间件:
'use strict'
const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../settings/config');
function isAuth(req, res, next) {
if (!req.headers.authotization) {
return res.status(403).send({
message: `No tiene autorizacion`
})
}
const token = req.headers.authotization.split(" ")[1];
const payload = jwt.decode(token, user, config.token.secret_token);
if (payload.exp <= moment().unix()) {
return res.status(401).send({
message: 'El token ha expirado'
})
req.user = payload.sub;
next();
}
}
module.exports = isAuth;
while this would be the route:虽然这将是路线:
'use strict'
const express = require('express');
const router = express.Router();
const auth = require('../middlewares/auth');
router.get('/', auth.isAuth, (req, res) => {
res.status(200).send({
message: `Tienes acceso`
})
})
on the other hand, this is my main application settings (app.js):另一方面,这是我的主要应用程序设置(app.js):
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const config = require('./config')
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
// Routes variables
const productRouter = require('../routes/product');
const privateRouter = require('../routes/private');
// Routes uses
app.use('/api/product', productRouter);
app.use('/private', privateRouter);
app.listen(config.app.port, err => {
if (err) throw err;
console.log(`Server listening on port ${config.app.port}`)
})
module.exports = app;
I am getting this error:我收到此错误:
D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\route.js:202 throw new Error(msg);
D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\route.js:202 throw new Error(msg); ^
^
Error: Route.get() requires a callback function but got a [object Undefined] at Route.
错误:Route.get() 需要一个回调函数,但在 Route 处得到一个 [object Undefined]。 [as get] (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\route.js:202:15) at Function.proto.
[as get] (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\route.js:202:15) 在 Function.proto 中。 [as get] (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\index.js:510:19) at Object.
[as get] (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\index.js:510:19) 在 Object. (D:\\api-rest-carlos-azaustre\\routes\\private.js:6:8) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Module.require (internal/modules/cjs/loader.js:852:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.
(D:\\api-rest-carlos-azaustre\\routes\\private.js:6:8) 在 Module._compile (internal/modules/cjs/loader.js:959:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js :727:14) at Module.require (internal/modules/cjs/loader.js:852:19) at require (internal/modules/cjs/helpers.js:74:18) at Object。 (D:\\api-rest-carlos-azaustre\\settings\\app.js:15:23) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Module.require (internal/modules/cjs/loader.js:852:19) at require (internal/modules/cjs/helpers.js:74:18) [nodemon] app crashed - waiting for file changes before starting...
(D:\\api-rest-carlos-azaustre\\settings\\app.js:15:23) 在 Module._compile (internal/modules/cjs/loader.js:959:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js :727:14) at Module.require (internal/modules/cjs/loader.js:852:19) at require (internal/modules/cjs/helpers.js:74:18) [nodemon] 应用程序崩溃 - 等待文件开始前的变化...
And sometimes this line is added at the top of error:有时这一行会添加在错误的顶部:
(node:3092) MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
(节点:3092)MaxListenersExceededWarning:检测到可能的 EventEmitter 内存泄漏。 11 exit listeners > added to [Bus].
11 个退出侦听器 > 添加到 [Bus]。 Use emitter.setMaxListeners() to increase limit
使用emitter.setMaxListeners() 增加限制
After reading the answers, I edit my question.阅读答案后,我编辑了我的问题。 I have placed only auth and not auth.isAuth and I am getting the following error:
我只放置了auth而不是 auth.isAuth 并且我收到以下错误:
D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\index.js:458 throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) ^
D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\index.js:458 throw new TypeError('Router.use() 需要一个中间件函数,但得到了一个 ' + gettype(fn)) ^
TypeError: Router.use() requires a middleware function but got a Object at Function.use (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\index.js:458:13) at Function.
类型错误:Router.use() 需要一个中间件函数,但在 Function.use (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\router\\index.js:458:13) 处有一个对象。 (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\application.js:220:21) at Array.forEach () at Function.use (D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\application.js:217:7) at Object.
(D:\\api-rest-carlos-azaustre\\node_modules\\express\\lib\\application.js:220:21) at Array.forEach() at Function.use (D:\\api-rest-carlos-azaustre\\node_modules\\ express\\lib\\application.js:217:7) 在对象。 (D:\\api-rest-carlos-azaustre\\settings\\app.js:20:5) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Module.require (internal/modules/cjs/loader.js:852:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.
(D:\\api-rest-carlos-azaustre\\settings\\app.js:20:5) 在 Module._compile (internal/modules/cjs/loader.js:959:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js :727:14) at Module.require (internal/modules/cjs/loader.js:852:19) at require (internal/modules/cjs/helpers.js:74:18) at Object。 (D:\\api-rest-carlos-azaustre\\index.js:3:13) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) [nodemon] app crashed - waiting for file changes before starting...
(D:\\api-rest-carlos-azaustre\\index.js:3:13) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal /modules/cjs/loader.js:995:10) 在 Module.load (internal/modules/cjs/loader.js:815:32) 在 Function.Module._load (internal/modules/cjs/loader.js:727) :14) [nodemon] 应用程序崩溃 - 在开始之前等待文件更改...
Does anybody know what is it due to?有人知道这是什么原因吗?
Yes, you export the function with this code: module.exports = isAuth;
是的,您使用以下代码导出函数:
module.exports = isAuth;
But then you call use it like this: auth.isAuth
但是然后你像这样调用使用它:
auth.isAuth
Assuming you're doing something like const auth = require('./bin/auth.js');
假设你正在做类似
const auth = require('./bin/auth.js');
or whatever管他呢
auth
would be the function itself -- there will be no isAuth
property. auth
将是函数本身——不会有isAuth
属性。
So you should try this:所以你应该试试这个:
router.get('/', auth, (req, res) => {
You haven't posted your entire code, so this is just a best guess.你还没有发布你的整个代码,所以这只是一个最好的猜测。
module.exports = isAuth;
means you're only exporting the function and nothing else.意味着你只导出函数而不是其他任何东西。 That means when you do
const auth = require('../middlewares/auth');
这意味着当你做
const auth = require('../middlewares/auth');
, auth
is the actual function, not an object containing isAuth
as a property. ,
auth
是实际的函数,而不是包含isAuth
作为属性的对象。
So, doing router.get('/', auth, (req, res) => {
should work, instead of auth.isAuth
which is invalid.所以,做
router.get('/', auth, (req, res) => {
应该有效,而不是无效的auth.isAuth
。
Learn more about modules here: https://js.evie.dev/modules在此处了解有关模块的更多信息: https : //js.evie.dev/modules
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.