通过节点服务器加载HTML页面时不显示图像

时间:2015-07-24 15:24:12

标签: javascript html node.js

抬头:我对Node.js很新,所以这段代码可能不是最好的方法。我还在学习过程中。

当我通过节点运行.JS文件并转到localhost:1337时,所有HTML都显示正确,但图像无法呈现。当我查看源代码时,图像将以文本/ HTML格式呈现,而不是图像。

这是为什么?这就是图像没有显示的原因吗?

到目前为止,这是我的代码。

var http    = require('http'),
fs      = require('fs'),
request = require('request'),
url     = require('url');


http.createServer(function (req, res)
  {
    console.log(req.url);
      var request  = url.parse(req.url, true),
          action   = request.pathname,
          html     = buildHtml(req);
      res.writeHead(200, {'Content-Type': 'text/html','Content-Length': html.length,'Expires': new Date().toUTCString()});
      res.end(html);
  }).listen(1337, '127.0.0.1');
  console.log('Server running at http://127.0.0.1:1337/');



function buildHtml(req)
{
  var header = "",
      body   = '<img src="../Dilbert.jpg" alt="Dilbert">';
  return '<!DOCTYPE html>'
       + '<html><header>' + header + '</header><body>' + body + '</body></html>';
};

var download = function(uri, filename, callback)
{
    request.head(uri, function(err, res, body)
    {
      console.log('content-type:', res.headers['content-type']);
      console.log('content-length:', res.headers['content-length']);
      request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
    });
};

download('http://assets.amuniversal.com/145cd9c0fb4e0132ee37005056a9545d', 'Dilbert.jpg', function(){
  console.log('done');
});

0 个答案:

没有答案