user462794 user462794 - 2 months ago 7
Node.js Question

How to use a middleware router for a sub path in express nodejs

I would like to sue a middleware just for the /doc path so it can serve satic file and have a basic auth.

But when i try to get /doc i have a cannot get /doc error.

Does anyone have any idea ?

var app = express();
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) ; // parse application/json
app.use(functio //app.use('/doc', express.static('./doc'));n(req, res, next) {
res.header("X-powered-by", "NodeJs");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
next();
});
app.use(function(req, res, next) {
console.log(' - ',req.originalUrl);
next();
});

var router = express.Router();

router.use(express.basicAuth('testUser', 'testPass'));

router.get('/doc', function(req, res, next) {
console.log("inside doc");
express.static('./doc');
next();
});

app.use('/conf',require('./v1/data_config'));


thanks and regard

Answer

2 Things: You have to add your router to your express app and you should move the '/doc' route outside of your router as authentication could interfere with your app.

var router = express.Router();
router.use(express.basicAuth('testUser', 'testPass'));
router.get('/', express.static('doc'));

app.use('/doc',router);
Comments