跳到主要内容
CNode

Node得到页面图片混乱

问答
WwestAnHui发布于 12 年前最后回复 12 年前
544150

本人初学node尝试了一个简单的静态服务器,仅仅返回一个拥有五张图片的页面,不过发现这五张图片的显示的不正确

var http = require("http"), fs = require("fs"), base = 'www/img/', mime = require("mime");

http.createServer(function(req, res){ pathname = base + req.url; var type = mime.lookup(pathname); console.log(pathname); fs.exists(pathname, function(exists){ if(exists){ var file = fs.readFile(pathname, "binary", function(err, data){ if(!err){ res.setHeader("Content-Type",type); res.write(data, "binary"); res.end(); }else{ console.log(err); } }) }else{ res.writeHead(404,{"Content-Type":"text/plain"}); res.write("Bad request 404\n"); res.end(); } }); }).listen(8080);

然后页面每一次刷新显示的图片都会不一样 这个是正确的时候 1.png 比如我再一次刷新 2.png 就会变成这样子,每一次刷新都有新的惊喜,但是看到html源码中对应的图片src都是正确的 这情况是不是因为回调冲突了这样的情况啊,求讲解。。。

查看回复

回复 (5)

G
gedy#512 年前

fs.exists(pathname, function(exists){ pathname }) 是个异步回调,等到响应过来之后,回调里的pathname已经不一定对应req.url了。加个匿名函数确保pathname对应上即可。

(function(pathname){
	fs.exists(pathname, function(exists){
		pathname
	})
})(pathname)
C
coolicer#412 年前

全部代码打包,帮你看一下

J
jx-zhou#312 年前

应该是异步的原因吧?你把你读取图片的方法改成同步的试试

W
westAnHui#212 年前
引用 coolicer图片的URL是怎么写的

@coolicer 和html文件在同一目录,图片的URL是相对定位。。我如果用node打开页面看源码哪怕图片显示的不对,可是我找到那个图片的元素结点,看它的URL,找过去却是对的,只不过显示出来的不对

C
coolicer#112 年前

图片的URL是怎么写的

参与回复

登录后即可参与回复。登录