简体   繁体   English

使用 Express JS 服务 static 前端 JS 文件

[英]Serving static frontend JS file with Express JS

Hi I am having trouble Loading the frontend JS file in Express server.您好,我在 Express 服务器中加载前端 JS 文件时遇到问题。 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 文件

HTML

But the script file index.js is not loading and i am not able to function但是脚本文件 index.js 没有加载,我无法加载 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:后端的“public”文件夹通常是指服务器上映射到 URL 根路径的文件夹。因此尝试在快速路由中将/static路径替换为/ ,并检查登录状态(以及任何其他 HTTP GET 请求处理不涉及服务 static 文件的服务器根路径)在设置 static 服务器本身之前:

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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