当我打开 html 文件并单击它时,它可以使用 background-image: url(),但是当我使用 res.sendFile() 在 expressapp 中打开该文件时,它不起作用。css 的其余部分代码在这两种情况下都正常工作,html 代码也能正常工作。总之,除了背景图像之外的所有东西都可以完美运行,所以我不认为问题出在其余代码或应用程序上,我认为只是背景图像在 express 应用程序中不起作用,所以我会想知道是否有解决此问题的解决方案,例如避免此问题的其他方法,或者也许我实际上为此做错了什么。我尝试将图像添加到我在应用程序中使用的 ejs 文件中,但它也不起作用,只有其余的 css 代码。
问题中不知道能不能加图,因为想加照片显示express app的文件夹和图片的路径,所以不得不说home.html文件和app .js 文件位于 Express 应用程序的文件夹内,图像位于该 Express 应用程序内,但与往常一样,位于在 Express 应用程序中创建的路径“/public/images”(来自 Express 应用程序文件夹)中。
我试过放置绝对路径,只有“/”开头和当前路径。我试图找到一个不同的解决方案,但我发现没有人遇到这个问题(通常它有效)或者可能是因为我发现不正确。
//home.html
//This is only the head of the html file
// the only important is the background-image: url(), that does not work
//in express.
<head>
<style>
body {
text-align: center;
background-image: url("./public/images/aghhome.jpg");
background-color: white;
background-repeat: no-repeat;
font-family: "Times New Roman", Times, serif;
}
h1 {
font-size: 50px;
border-style: solid;
background-color: black;
color: white;
}
button {
font-size: 50px;
}
</style>
</head>
//app.js
// the main js file of the express app
// this a part of the code where I open this file by sendFile()
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/home.html'));
});
我希望当我使用 express 应用程序时图像会显示为背景,而不仅仅是当我直接在文件系统中打开 html 文件时。
最佳答案
你可以试试:
//home.html
//This is only the head of the html file
// the only important is the background-image: url(), that does not work
//in express.
<head>
<style>
body {
text-align: center;
background-image: url("./images/aghhome.jpg");
background-color: white;
background-repeat: no-repeat;
font-family: "Times New Roman", Times, serif;
}
h1 {
font-size: 50px;
border-style: solid;
background-color: black;
color: white;
}
button {
font-size: 50px;
}
</style>
</head>
//app.js
// the main js file of the express app
// this a part of the code where I open this file by sendFile()
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/home.html'));
});
关于html - 背景图像 : url() does not work when you open the html by an express app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584788/