在node.js中放置图像文件的位置

Where to put the image file in node.js?

本文关键字:图像 文件 位置 node js      更新时间:2023-09-26

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

/home/nikhil/test_img/

  • server.js
  • page.html
  • pic.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的任何请求时显示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加载页面时,图像没有显示出来。但是,当我通过浏览器(不是通过节点)打开网页时,图像就会显示出来。

我也尝试将src更改为

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

另外,我尝试使用<script>alert(document.location.pathname);</script>

在javascript中打印我的位置

打印的路径是

/

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

/home/nikhil/test_img/page.html

我需要把这个工作的图像文件在哪里?

你的代码说,每个请求应该服务的文件对应于filePath即html文件page.html。这对于页面请求本身是可以的,但是html页面中的img标记为图像pic.jpg创建了一个单独的请求,该图像应该存在于与页面相同的路径中。但是,不是提供img文件,这意味着您的请求处理程序将返回头为Content-type: image/jpg的内容,您的请求处理程序再次响应html页面的内容和头为Content-Type:text/html