当前位置: 代码迷 >> JavaScript >> nodejs入门之使用nodejs显示一个网页
  详细解决方案

nodejs入门之使用nodejs显示一个网页

热度:699   发布时间:2013-12-26 00:35:35.0
nodejs入门之使用nodejs展示一个网页

转自:http://blog.csdn.net/zxsrendong/article/details/15504729

?

一个网页的内容其实就是一段字符串,response.write()可以接受一个字符串作为参数,所以很明显只需要把一个网页的内容作为参数传递给response.write()即可。例如:

[javascript]?view plaincopy
?
  1. <span?style="white-space:pre">??</span>var?http?=?require('http');??
  2. ????http.createServer(function(req,?res){??
  3. ????????var?html?=?'<html>'??
  4. ????????+'<head>'??
  5. ????????+'<title>nodejs</title>'??
  6. ????????+'</head>'??
  7. ????????+'<body>'??
  8. ????????+???'hello?world!?1234'??
  9. ????????+'</body>'??
  10. ????????+'</html>';??
  11. ????????res.writeHead(200,{'Content-Type'?:?'text/html'});??
  12. ????????res.write(html);??
  13. ????????res.end();??
  14. ????}).listen(8888);??

在浏览器地址栏输入127.0.0.1:8888查看结果,打开控制台,可以发现网页的类容已经全部包含在浏览器中。
一个网页一般会包含css样式文件和javascript脚本文件,再上一个示例中没有这两个文件。现在可以添加简单的css和javascript文件查看效果:

[javascript]?view plaincopy
?
  1. <span?style="white-space:pre">??</span>var?http?=?require('http');??
  2. ????http.createServer(function(req,?res){??
  3. ????????var?html?=?'<html>'??
  4. ????????+'<head>'??
  5. ????????+'<title>nodejs</title>'??
  6. ????????+'<link?rel="stylesheet"?type="text/css"?href="./bootstrap/css/bootstrap.min.css"?/>'??
  7. ????????+'<script?type="text/javascript"?src="./bootstrap/js/bootstrap.min.js"></script>'??
  8. ????????+'</head>'??
  9. ????????+'<body>'??
  10. ????????+???'hello?world!hello?world!?1234'??
  11. ????????+'</body>'??
  12. ????????+'</html>';??
  13. ????????res.writeHead(200,{'Content-Type'?:?'text/html'});??
  14. ????????res.write(html);??
  15. ????????res.end();??
  16. ????}).listen(8888);??

会发现css文件和javascript文件都没有被正确下载。这是因为这段代码中规定的'Content-Type'都是'text/html'类型,而且所有的response内容都相同,当然就看不到想要的效果。
我们知道css样式和javascript脚本有多种不同的引入方法,css样式可以使用外联样式、内部样式和内联样式,javascript可以使用外联和内部两种,既然外联不能正确显示,那么可以尝试其他方法。通过测试可以发现css内部样式和内联样式都可以在网页上看到效果,javascript同样。

[javascript]?view plaincopy
?
  1. <span?style="white-space:pre">??</span>var?http?=?require('http');??
  2. ????http.createServer(function(req,?res){??
  3. ????????var?html?=?'<html>'??
  4. ????????+'<head>'??
  5. ????????+'<title>nodejs</title>'??
  6. ????????+'<style?type="text/css">'??
  7. ????????+'body{color:red;}'??
  8. ????????+'</style>'??
  9. ????????+'</head>'??
  10. ????????+'<body>'??
  11. ????????+???'hello?world!?1234'??
  12. ????????+'</body>'??
  13. ????????+'</html>';??
  14. ????????res.writeHead(200,{'Content-Type'?:?'text/html'});??
  15. ????????res.write(html);??
  16. ????????res.end();??
  17. ????}).listen(8888);??

可以看到浏览器中的文字显示为红色。
但是这两种方式都不是现代web开发所提倡的。现代web开发提倡css样式和javascript使用外联的方式,以方便管理和重用。css文件和javascript文件都是静态文件,我们可以尝试建立一个简单的静态文件服务,这样就可以正确的在网页中使用外联文件了。