简体   繁体   中英

Serving static frontend JS file with Express JS

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

文件结构

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

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

});

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