peiyuan1030 发表于 2017-2-21 11:00:44

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

  转自:http://blog.csdn.net/zxsrendong/article/details/15504729
  一个网页的内容其实就是一段字符串,response.write()可以接受一个字符串作为参数,所以很明显只需要把一个网页的内容作为参数传递给response.write()即可。例如:
 view plaincopy 



[*]<span style="white-space:pre">  </span>var http = require('http');  
[*]    http.createServer(function(req, res){  
[*]        var html = '<html>'  
[*]        +'<head>'  
[*]        +'<title>nodejs</title>'  
[*]        +'</head>'  
[*]        +'<body>'  
[*]        +   'hello world! 1234'  
[*]        +'</body>'  
[*]        +'</html>';  
[*]        res.writeHead(200,{'Content-Type' : 'text/html'});  
[*]        res.write(html);  
[*]        res.end();  
[*]    }).listen(8888);  

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

 view plaincopy 



[*]<span style="white-space:pre">  </span>var http = require('http');  
[*]    http.createServer(function(req, res){  
[*]        var html = '<html>'  
[*]        +'<head>'  
[*]        +'<title>nodejs</title>'  
[*]        +'<link rel="stylesheet" type="text/css" href="./bootstrap/css/bootstrap.min.css" />'  
[*]        +'<script type="text/javascript" src="./bootstrap/js/bootstrap.min.js"></script>'  
[*]        +'</head>'  
[*]        +'<body>'  
[*]        +   'hello world!hello world! 1234'  
[*]        +'</body>'  
[*]        +'</html>';  
[*]        res.writeHead(200,{'Content-Type' : 'text/html'});  
[*]        res.write(html);  
[*]        res.end();  
[*]    }).listen(8888);  

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

 view plaincopy 



[*]<span style="white-space:pre">  </span>var http = require('http');  
[*]    http.createServer(function(req, res){  
[*]        var html = '<html>'  
[*]        +'<head>'  
[*]        +'<title>nodejs</title>'  
[*]        +'<style type="text/css">'  
[*]        +'body{color:red;}'  
[*]        +'</style>'  
[*]        +'</head>'  
[*]        +'<body>'  
[*]        +   'hello world! 1234'  
[*]        +'</body>'  
[*]        +'</html>';  
[*]        res.writeHead(200,{'Content-Type' : 'text/html'});  
[*]        res.write(html);  
[*]        res.end();  
[*]    }).listen(8888);  

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