在哪里把图像文件在node.js?

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

/家庭/ 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); }); 

这只需创build显示page.html的任何请求localhost:8889的服务器

代码为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>打印我的位置

打印的path是

/

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

/home/nikhil/test_img/page.html

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

你的代码说每个请求都应该提供对应于filePath的文件,即html文件page.html 。 这对于页面请求本身是很好的,但是你的html页面中的img标签会为图片pic.jpg创build一个单独的请求,它应该和页面存在于相同的path中。 但不是提供img文件,这意味着你的请求处理程序将返回一些头Content-type: image/jpg ,你的请求处理程序再次响应html页面的内容和头Content-Type:text/html

您需要根据所要求的内容区分要提供的服务。