英文:
Serving static frontend JS file with Express JS
问题
我在Express服务器中加载前端JS文件时遇到了问题。我的文件结构如下:
我的服务器代码 -
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) => {
// 检查用户是否已登录,通过检查cookie
let username = req.cookies.username;
if(username){
return res.sendFile(path.join(__dirname, "public/index.html"))
}else{
res.redirect("/login");
}
});
我可以成功加载HTML文件。
但是脚本文件index.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
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
答案1
得分: 1
"public"文件夹在后端通常指的是服务器上映射到URL根路径的文件夹。因此,尝试在express路由中将/static
路径替换为/
,并在设置静态服务器之前进行已登录状态的检查(以及任何不涉及提供静态文件的服务器根路径的其他HTTP GET请求处理):
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) => {
// 检查用户是否已登录,通过检查cookie
let username = req.cookies.username;
if(username){
return res.sendFile(path.join(__dirname, "public/index.html"))
}else{
res.redirect("/login");
}
// 在根路径上设置静态服务器:
app.use('/', express.static(path.join(__dirname, 'public')))
});
英文:
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')))
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论