我正在努力学习节点的细节。我知道您可以使用框架提供文件,但我正在尝试手动执行此操作。我在' ./ public / logo.jpg'中有一个jpeg文件。当我通过localhost:8080发送请求时,我无法获取图像,只是一个带有通用图像占位符的空白屏幕。我究竟做错了什么?谢谢!
var http=require('http');
var url=require('url');
var fs=require('fs');
// creates a new httpServer instance
http.createServer(function (req, res) {
// this is the callback, or request handler for the httpServer
log('in server callback')
res.ins=res.write;
var parse=url.parse(req.url,true);
var path0=parse.pathname;
console.log(path0)
// respond to the browser, write some headers so the
// browser knows what type of content we are sending
var serveFile=function(){
var path='./public'+path0
fs.exists(path,function(e){
if(e){
log('serving file')
log(path)
fs.readFile(path,'binary',function(err,data){
if(data){
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.ins(data)
res.end()
}
})
}
else{
log('no file to serve')
log(path)
servePage()
}
})
}
serveFile()
}).listen(8080); // the server will listen on port 8080
答案 0 :(得分:0)
只需更改readFile
回调中的以下两行:
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.write(data, 'binary');
使用response.write
将数据发送到客户端并将编码设置为binary
。 (默认为utf-8)