0

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

2
  • Did you mean <script src="static/index.js"></script>? Commented Jan 10, 2023 at 20:49
  • You're using app.use('/static', express.static(path.join(__dirname, 'public'))), which means static is your path and public is your local directory. Try using <script src="/static/index.js"></script>. Commented Jan 10, 2023 at 20:52

1 Answer 1

1

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

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.