user462794 user462794 - 1 year ago 62
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");
app.use(function(req, res, next) {
console.log(' - ',req.originalUrl);

var router = express.Router();

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

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


thanks and regard

Answer Source

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'));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download