简体   繁体   English

如何在节点+ Express应用中设置路由以通过身份验证方法?

[英]How do I set up routes in my node + express app to pass an authenticate method?

I'm following the auth0 backend set up tutorial, and I'm wondering how I can set up my routes in a separate file instead of in app.js . 我正在遵循auth0后端设置教程,并且想知道如何在单独的文件而不是app.js设置路由。

In the tutorial, they create 在教程中,他们创建

var authenticate = jwt({
  secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
  audience: process.env.AUTH0_CLIENT_ID
});

and then app.use('/secured', authenticate); 然后app.use('/secured', authenticate);

If I want to set up my routes in some routes folder routes/index.js , and I want to use this authenticate() , how can I set that up in my app.js ? 如果我想在某些路由文件夹“ routes/index.js设置路由,并且想使用此authenticate() ,如何在app.js

I know I have to do something like var routes = require('./routes/index.js'); 我知道我必须做一些类似var routes = require('./routes/index.js');事情var routes = require('./routes/index.js'); , but how do I set up the app.use( .. ) in this case so it uses authenticate() ? 但是,在这种情况下,如何设置app.use( .. ) ,使其使用authenticate()

Thanks 谢谢

You can define a routes module in ./routes/index.js like this: 您可以在./routes/index.js定义一个routes模块,如下所示:

// ./routes/index.js

module.exports = function (app) {
   app.get('/secured', getSecuredController);
};

function getSecuredController (req, res) {
   res.send('/secured OK');
}

And in your main app.js file: 在主app.js文件中:

// ./app.js

var initializeRoutes = require('./routes');
var authenticate = jwt({..});

app.use('/secured', authenticate);
initializeRoutes(app);

You can return router from file routes/index.js: 您可以从文件route / index.js返回路由器:

// routes/index.js

const express = require('express');

module.exports = function(options) {
    const router = express.Router();

    router.get('/', (req, res, next) => {
        // process route...
    });

    // define other routes...

    return router;
};

And the use it in server: 并在服务器中使用它:

// server.js

const express = require('express');
const router = require('./routes/index.js');

const authenticate = jwt({
  secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
  audience: process.env.AUTH0_CLIENT_ID
});

var app = express()

app.use('/secured', authenticate, router());

This will make your router configurable and reusable. 这将使您的路由器可配置和可重用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM