Cannot use basic authentication while serving static files using express

前端 未结 4 1959
谎友^
谎友^ 2021-02-12 19:29

Using the Express framework for node.js, I\'m trying to serve up static files contained in a directory while also putting basic authentication on it. When I do so, I am prompted

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-12 19:47

    app.use doesn't let you chain middlewares in that way. The various app.VERB functions do, but app.use doesn't. That's for one middleware at a time.

    If you split the 2 middlewares out into separate calls, you should get the results you want:

    app.use('/admin', auth)
    app.use('/admin', express.static(__dirname + '/admin'));
    

    EDIT

    As of express version 4.x you can pass in multiple middlewares as an array, or arguments, or mixture of both into app.use. Making static files authorization safe would now be:

    app.use( "/admin", [ auth, express.static( __dirname + "/admin" ) ] );
    

    But both ways are still perfectly valid.

提交回复
热议问题