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

后端 未结 1 659
花落未央
花落未央 2021-02-04 08:05

I\'m using Express 4 where I have a route protected by passport.js, like this:

var media = require(\'express\').Router();

media.get(\'/\', function(req, res) {
         


        
1条回答
  •  囚心锁ツ
    2021-02-04 08:47

    You could split your router up into protected/unprotected and call the middleware on the protected routes.

    var express = require('express'),
        media = express.Router(),
        mediaProtected = express.Router();
    
    media.get('/', function(req, res) {
        // provide results from db
    });
    
    mediaProtected.post('/', function(req, res) {
        // This route is auth protected
    });
    
    module.exports = {
        protected: mediaProtected,
        unprotected: media
    };
    

    And then you can do

    var router = require('./my-router');
    app.use('/api/route', passport.authenticate('bearer'), router.protected);
    app.use('/api/route', router.unprotected);
    

    0 讨论(0)
提交回复
热议问题