gpt4 book ai didi

javascript - 将图像文件放在 node.js 中的什么位置?

转载 作者:行者123 更新时间:2023-11-28 03:23:39 24 4
gpt4 key购买 nike

我在 Linux 中有以下目录结构,其中只有 3 个文件:

/home/nikhil/test_img/

  • 服务器.js
  • page.html
  • 图片.jpg

这是一个简单的 node.js hello world 设置,不使用 express 或任何其他库

server.js 代码

var http = require("http"), fs = require('fs');
var path = require('path');
var root = path.dirname(require.main.filename);
var filePath = path.join(root + '/page.html');

var port = 8889;

function onRequest(request, response) {
fs.readFile(filePath, function (err, html) {
if (err) {
throw err;
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(html);
response.end();
});
}

http.createServer(onRequest).listen(port, function () {
console.log("Server has started at port " + port);
});

这只是创建了一个服务器,它在对 localhost:8889 的任何请求中显示 page.html

page.html 的代码

<html>
<head><title>Page</title></head>

<body>
<h1> Hello World </h1>
<img src="pic.jpg" alt="image">
</body>

</html>

这是一个带有 Hello World 标题和图像的简单网页。

现在,错误是当我在浏览器上点击 localhost:8889 时加载页面时图像没有显示。但是,当我只是通过浏览器(而不是通过 Node )打开网页时,就会显示图像。

我也尝试过将 src 更改为

  • “/home/nikhil/test_img/page.html”
  • “文件:///home/nikhil/test_img/page.html”
  • “localhost:8889/page.html”但是,这些都不起作用

此外,我尝试使用 <script>alert(document.location.pathname);</script> 在 javascript 中打印我的位置

打印的路径是

/

然而,当我直接在浏览器中运行页面时(没有 Node ),它是

/home/nikhil/test_img/page.html

我需要将图像文件放在哪里才能使其正常工作?

最佳答案

您的代码表明每个请求都应提供与 filePath 对应的文件,即 html 文件 page.html。这对页面请求本身没问题,但是 html 页面中的 img 标记会为图像 pic.jpg 创建一个单独的请求,该图像应该与页。但不是提供 img 文件,这意味着您的请求处理程序将返回带有 header Content-type: image/jpg 的内容,您的请求处理程序再次响应 html 页面的内容和 header Content-类型:文本/html

您需要根据请求区分要提供的服务。

关于javascript - 将图像文件放在 node.js 中的什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606433/

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