Search code examples
htmlnode.jsexpressejsstatic-files

Express server static ejs file with css and js does not work


I am trying to make a website with node js , and I have /home and /contact. Every thing works until I put css and js at both of them and the second call does not work.I am reffering that I acces first the /home (everything works), then I do /contact and the page remains the same.

const PORT = 7777;

app.set('view engine','ejs');

app.get('/home',(req,res)=> {
    console.log("get /home");
    app.use(require("express").static('./views/Home'));
    res.render('Home/home.ejs');
});

app.get('/contact',(req,res)=>{
    console.log("get /contact");
    app.use(require("express").static('./views/Contact'));
    res.render('Contact/contatct.ejs');
});

app.listen(
    PORT,
    () => console.log(`it's alive on http://localhost:${PORT}`)
)

thx in advance


Solution

    • Do not require express multiple times. Do require express once at the top of your module
    • Do not add middleware in response to a request for a specific page. Do add it when the application loads.
    • Do not mix your view templates with your static files
    app.set('view engine','ejs');
    
    app.get('/home',(req,res)=> {
        console.log("get /home");
        res.render('Home/home.ejs');
    });
    
    app.get('/contact',(req,res)=>{
        console.log("get /contact");
        res.render('Contact/contatct.ejs');
    });
    
    app.use("/static", express.static('./static/'));
    

    Then in your EJS templates:

    <link rel="stylesheet" href="/static/file_name_in_static_folder.css">
    

    Or

    <img src="/static/image_used_in_one_template_but_stored_in_static_folder.png">