为什么我不能在我的Express路由中使用中间件?

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

Why can't I use middleware in my express route?

问题

我正在创建一个API,所以我想添加一个用户系统并验证对API的访问。

这将是用于验证的中间件:

'use strict'

const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../settings/config');

function isAuth(req, res, next) {
    if (!req.headers.authorization) {
        return res.status(403).send({
            message: '没有授权'
        })
    }
    const token = req.headers.authorization.split(" ")[1];
    const payload = jwt.decode(token, config.token.secret_token);

    if (payload.exp <= moment().unix()) {
        return res.status(401).send({
            message: '令牌已过期'
        })
    }

    req.user = payload.sub;
    next();
}

module.exports = isAuth;

而这将是路由:

'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: '您已获得访问权限'
    })
})

另外,这是我的主应用程序设置(app.js):

const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');

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

// 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));

// 路由变量
const productRouter = require('../routes/product');
const privateRouter = require('../routes/private');

// 使用路由
app.use('/api/product', productRouter);
app.use('/private', privateRouter);

app.listen(config.app.port, err => {
    if (err) throw err;
    console.log(`服务器在端口 ${config.app.port} 上监听`)
})

module.exports = app;

您遇到的错误是因为您在路由中使用了auth.isAuth,但在中间件文件中导出的是isAuth函数,所以应该这样修改:

router.get('/', auth, (req, res) => {
    res.status(200).send({
        message: '您已获得访问权限'
    })
})

这应该解决您的问题。如果还有其他问题,请告诉我。

英文:

I am creating an API, so I want to add a user system and validate access to the API.

This would be the middleware for validation:

&#39;use strict&#39;

const jwt = require(&#39;jwt-simple&#39;);
const moment = require(&#39;moment&#39;);
const config = require(&#39;../settings/config&#39;);

function isAuth(req, res, next) {
    if (!req.headers.authotization) {
        return res.status(403).send({
            message: `No tiene autorizacion`
        })
    }
    const token = req.headers.authotization.split(&quot; &quot;)[1];
    const payload = jwt.decode(token, user, config.token.secret_token);

    if (payload.exp &lt;= moment().unix()) {
        return res.status(401).send({
            message: &#39;El token ha expirado&#39;
        })

        req.user = payload.sub;
        next();

    }
}

module.exports = isAuth;

while this would be the route:

    &#39;use strict&#39;
    const express = require(&#39;express&#39;);
    const router = express.Router();
    const auth = require(&#39;../middlewares/auth&#39;);
    
    router.get(&#39;/&#39;, auth.isAuth, (req, res) =&gt; {
        res.status(200).send({
            message: `Tienes acceso`
        })
    })

on the other hand, this is my main application settings (app.js):

const express = require(&#39;express&#39;);
const bodyParser = require(&#39;body-parser&#39;);
const morgan = require(&#39;morgan&#39;);

const app = express();
const config = require(&#39;./config&#39;)

// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan(&#39;dev&#39;));

// Routes variables
const productRouter = require(&#39;../routes/product&#39;);
const privateRouter = require(&#39;../routes/private&#39;);

// Routes uses
app.use(&#39;/api/product&#39;, productRouter);
app.use(&#39;/private&#39;, privateRouter);

app.listen(config.app.port, err =&gt; {
    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);
> ^
>
> Error: Route.get() requires a callback function but got a [object
> Undefined]
> at Route.<computed> [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202:15)
> at Function.proto.<computed> [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:510:19)
> at Object.<anonymous> (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.<anonymous> (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...

And sometimes this line is added at the top of error:
> (node:3092) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners > added to [Bus]. Use emitter.setMaxListeners() to increase limit

After reading the answers, I edit my question. I have placed only auth and not auth.isAuth and I am getting the following error:

> 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))
> ^
>
> 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.<anonymous> (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:220:21)
> at Array.forEach (<anonymous>)
> at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:217:7)
> at Object.<anonymous> (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.<anonymous> (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...

Does anybody know what is it due to?

答案1

得分: 1

你可以使用以下翻译部分:

是的,你可以使用这段代码导出该函数:module.exports = isAuth;

但是之后你要像这样调用它:auth.isAuth

假设你正在做类似这样的事情:const auth = require('./bin/auth.js'); 或者其他什么方式

auth 将会是函数本身,不会有 isAuth 属性。

所以你可以尝试这样做:

router.get('/', auth, (req, res) => {

由于你没有发布你的整个代码,所以这只是一个最佳猜测。

英文:

Yes, you export the function with this code: module.exports = isAuth;

But then you call use it like this: auth.isAuth

Assuming you're doing something like const auth = require(&#39;./bin/auth.js&#39;); or whatever

auth would be the function itself -- there will be no isAuth property.

So you should try this:

router.get(&#39;/&#39;, auth, (req, res) =&gt; {

You haven't posted your entire code, so this is just a best guess.

答案2

得分: 1

module.exports = isAuth; 表示你只导出这个函数,没有其他内容。这意味着当你使用 const auth = require('../middlewares/auth'); 时,auth 就是实际的函数,而不是包含 isAuth 作为属性的对象。

因此,应该使用 router.get('/', auth, (req, res) => { 而不是无效的 auth.isAuth

在这里了解更多关于模块的信息:https://js.evie.dev/modules

英文:

module.exports = isAuth; means you're only exporting the function and nothing else. That means when you do const auth = require(&#39;../middlewares/auth&#39;);, auth is the actual function, not an object containing isAuth as a property.

So, doing router.get(&#39;/&#39;, auth, (req, res) =&gt; { should work, instead of auth.isAuth which is invalid.

Learn more about modules here: https://js.evie.dev/modules

huangapple
  • 本文由 发表于 2020年1月3日 23:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581508.html
匿名

发表评论

匿名网友

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

确定