gpt4 book ai didi

javascript - 在 Node.js 中通过相对路径显示图像

转载 作者:行者123 更新时间:2023-12-02 13:56:45 25 4
gpt4 key购买 nike

我正在构建我的第一个 Node.js MVC 应用程序( native Node ,不使用 Express),但在通过相对路径显示 html 文件中的图像时遇到问题。

我将省去您的 server.js 和 router.js 代码,但这是我的 Controller 代码,这基本上就是我加载 View 的方式:

var fs = require("fs");
var controller = require("controller");

var load_view = 'view_home';
var context = { foo : 'bar' };

controller.load_view(res, req, fs, load_view, context);

这被传递给...

var url         = require('url');
var Handlebars = require('handlebars');

function load_view(res, req, fs, view, context, session){

// Files to be loaded, in order
var files = [
'view/elements/head.html',
'view/elements/header.html',
'view/' + view +'.html',
'view/elements/footer.html'
];

// Start read requests, each with a callback that has an extra
// argument bound to it so it will be unshifted onto the callback's
// parameter list
for(var i=0; i<files.length; ++i)
fs.readFile(files[i], handler.bind(null, i));

var count = 0;

function handler(index, err, content) {

// Make sure we don't send more than one response on error
if(count < 0) return;
if(err) {
count = -1;
console.log('Error for file: ' + files[index]);
console.log(err);
res.writeHead(500);
return res.end();
}

// Reuse our `files` array by simply replacing filenames with
// their respective content
files[index] = content;


// Check if we've read all the files and write them in order if
// we are finished
if(++count===files.length) {
res.writeHead(200, { 'Content-Type': 'text/html' });
for(var i = 0; i < files.length; ++i) {

var source = files[i].toString('utf8');

// Handlebars
var template = Handlebars.compile(source);
var html = template(context);

res.write(html); /* WRITE THE VIEW (FINALLY) */

}
res.end();
}

} // handler()

} // load()

最后,这是我的 html,在 src 属性中带有标签和相对路径:

<div class="help">

<img src="../public/img/test.jpg" />

</div>

与上述相关的我的文件系统如下:

我确信相对路径是正确的,但已经尝试了相对路径甚至绝对路径的所有组合。但仍然没有显示任何图像。

来自 LAMP 背景,访问文件树中的图像是微不足道的,但我意识到这里的服务器设置有很大不同(因为我是设置它的人)。

我通过创建一个单独的 Controller 来显式加载这些文件并使用 URI 访问该 Controller 来访问文件系统中的其他文件(如样式表)。但这种方法对于不确定数量的图像来说是不切实际的。

如何使用 Node.js 访问和显示文件系统中的图像?

最佳答案

I access other files (like stylesheets) in the filesystem by creating a separate controller to load those files explicitly and access that controller using a URI.

您需要有一个 Controller 。这就是代码将浏览器请求的 URL 转换为响应的方式。

But this approach in impractical for an indeterminate number of images.

然后写一个通用的。将与其他 Controller 不匹配的所有 URL、以特定路径开头、以 .jpg 结尾的 URL 或任何您喜欢的逻辑转换为基于 URL 的文件路径。

读取文件的内容并输出合适的 HTTP header (包括正确的内容类型),后跟数据。

关于javascript - 在 Node.js 中通过相对路径显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com