Home > Software engineering >  Serving static frontend JS file with Express JS
Serving static frontend JS file with Express JS

Time:01-15

Hi I am having trouble Loading the frontend JS file in Express server. My file structure is like this

File Structure

My Server Code -

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use('/static', express.static(path.join(__dirname, 'public')))
app.get("/", (req, res) => {
    // check if user is logged in, by checking cookie
    let username = req.cookies.username;
    if(username){
        return res.sendFile(path.join(__dirname, "public/index.html"))
    }else{
        res.redirect("/login");
    }

});

I can successfully Load the html file

HTML

But the script file index.js is not loading and i am not able to function

<script src="index.js"></script>

Can you tell me what is it i am doing wrong

CodePudding user response:

The "public" folder on the back end usually refers to a folder on the server mapped to the root path of the URL. Hence try replacing the /static path with just / in express routing, and put checks for logged in status (and any other HTTP GET request processing for server root paths that does not involve serving static files) before setting up the static server itself:

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use('/static', express.static(path.join(__dirname, 'public')))
app.get("/", (req, res) => {
    // check if user is logged in, by checking cookie
    let username = req.cookies.username;
    if(username){
        return res.sendFile(path.join(__dirname, "public/index.html"))
    }else{
        res.redirect("/login");
    }

 // set up static server on root path:

    app.use('/', express.static(path.join(__dirname, 'public')))

});
  • Related