简体   繁体   中英

is it the only way to use express.static?

i'm developing web site like below

webpage
    -app
        -routers
            -photo.js
    -public
        -css
            -photo.css
        -views
            -photo.ejs
    -server.js

when i connect to i had no problem. 我没有问题。 but, when i connect to i couldn't get css so, i add this three line 我无法得到CSS,所以我添加了这三行

app.use('/photo/4din2d',express.static(__dirname + '/public'));
app.use('/photo/tree',express.static(__dirname + '/public'));
app.use('/photo/hero',express.static(__dirname + '/public'));

this is problem, i'm going to add more category like and i think add express.static everytime is not a good way. 并且我认为每次添加express.static都不是一个好方法。 please give me the right way.

photo.js

router.get('/', (req,res)=>{ res.render('photo'); }); router.get('/:id',(req,res)=>{ var category = req.params.id; res.render('photo'); });

photo.ejs

    <link rel="stylesheet" href="./css/photo.css">

server.js

    app.use(express.static(__dirname + '/public'));
    app.use('/photo',express.static(__dirname + '/public'));
    app.use('/photo/4din2d',express.static(__dirname + '/public'));
    app.use('/photo/tree',express.static(__dirname + '/public'));
    app.use('/photo/hero',express.static(__dirname + '/public'));

    var photo = require('./app/routers/photo.js');
    app.use('/photo',photo);

In server.js , you only need the one static directory, public :

app.use(express.static(__dirname + '/public'))

Then in photo.ejs , you should reference your assets relative to the root ( / ) rather than relative to the current route ( ./ ):

<link rel="stylesheet" href="/css/photo.css">

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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