Express app.use()与2个中间件不能一起使用

时间:2019-10-16 05:27:55

标签: express

我正在尝试将“基本身份验证”或“承载者令牌”应用于所有以“ / auth”开头的路由

在同一路由器文件“ routes / auth.js”中,我准备了两种路由器类型,并将它们一起导出。然后在“ app.js”中,我尝试将两个中间件都应用到“ app.use()”。

结果是,不是两种类型都同时工作。仅第一位置中间件会影响所有“ / auth”路由,即:-

app.use('/auth', [affecting-all-auth-routes, no-effect-on-all-auth-routes]);

这些是我尝试过的参考网站: http://expressjs.com/zh-tw/api.html#app.use

app.use('/', [r1, r2]);

What is a better way to authenticate some of the routes on Express 4 Router?

我猜可能是由于某些语法错误。你能给我个主意吗?

// app.js

const express = require('express');

const authRouter = require('./routes/auth');

const app = express();

app.use('/auth', [authRouter.basic, authRouter.bearer]);

//路由/auth.js

const express = require('express');
var routerBasic = express.Router();
var routerBearer = express.Router();

const basicAuth = require('express-basic-auth');
const jwtProtected = require('./middleware/jwToken');

routerBasic.use(basicAuth({
    users: { 'admin': '1234' }
}))
routerBearer.use(jwtProtected);

const login = require('../controllers/Auth/Basic/login');
const tokenRevoke = require('../controllers/Auth/Token/revoke-token');

routerBasic.post('/login', login);
routerBearer.post('/token/revoke', tokenRevoke);

module.exports = {
    basic: routerBasic,
    bearer: routerBearer
}

1 个答案:

答案 0 :(得分:0)

经过几天的研究,我终于得到了答案。

我不能在路由器级别上分离身份验证类型,而应该在路由级别上:-

router.post('/login', basicAuthFunctionHere, login);
router.post('/token/revoke', jwtAuthFunctionHere, tokenRevoke);