【发布时间】:2019-08-23 14:34:27
【问题描述】:
我正在尝试使用 EJS 开发一个非常简单的 NodeJS 服务器。 这个小服务器必须渲染一个小 HTML 页面,里面只有一行文本和一个 jpg 文件。
一切正常,但 jpg 文件:这不是由服务器加载的。
在代码中我指定了 express.static 路径但无事可做。
我在本地(在我的 2 台计算机上)尝试过,在这里,在我家中,一切正常。在远程服务器上,尚未加载 jpg。 我尝试了 2 个不同提供商的 2 个不同服务器,但结果是一样的。
这是我的 image.js 文件
const http = require("http")
var url = require("url")
const express = require("express");
const appExpress = express();
const router = express.Router();
const application_root = __dirname;
const application_port = 5000
appExpress.engine("html", require('ejs').renderFile);
appExpress.use("/", router);
appExpress.use(express.static(application_root + "/public"));
appExpress.get("*", function (req, res, next) {
res.render((application_root + "/public/indice.html"), {})
next();
});
// *********** CARICAMENTO PAGINA PRINCIPALE *************
function caricaPagina(res, tipologia_domande) {
res.render((application_root + "/public/indice.html"), {})
}
appExpress.listen(application_port, (req, res) => {
console.log(`Listening on port ${application_port}`);
})
这是我的 index.html 文件
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="UTF-8">
<title>Prova caricamento immagine</title>
</head>
<body>
<div><img src="public/images/Sfondi/Slider.jpg"></div>
Testo di prova per caricamento pagina
</body>
</html>
正如你所看到的,这个项目非常简单而且很小,但我很喜欢它:-(
感谢任何会帮助我的人:-)
* 更新 *
我试图运行这段代码
appExpress.get('/', (req, res) => res.sendFile(application_root + '/public/images/Sfondi/Slider.jpg'));
这段代码没问题,图像已正确加载。 所以这不是路径问题,而是 html 加载问题。 html和图片文件有res.render()问题吗?
* 更新 2 *
好的,情况是这样的: 如果我使用此代码(带有 sendFile 函数)中间件 加载 html 页面 加载图像但 不执行 html 页面内的 javascript 代码。
res.sendFile(path.join(__dirname + "/public/indice.html"), {path_image:path_image})
如果我选择使用此代码 (res.render) 中间件 在 html 页面内执行 javascript 但 不加载 图像。
res.render((application_root + "/public/indice.html"), {path_image:path_image})
有人对这个令人难以置信的问题有一些解决方案吗?我阅读了所有的网络,但似乎我是唯一一个遇到这个问题的人。
非常感谢:-)
【问题讨论】:
-
错字:您在文件路径中有
public两次。一次来自 URL,再次来自static的配置 -
旁白:
const router = express.Router();和appExpress.use("/", router);毫无意义。你没有给它附加任何路由。 -
@JonasWilms — 1.
<img src="public/2.static(application_root + "/public")); -
@JonasWilms — 静态模块的重点是将文件夹结构与 URL 关联起来。
-
@JonasWilms — 我想你误解了我的意思。代码尝试访问的文件路径中有两个
publics。 真正的文件路径可能没有。
标签: javascript node.js ejs