之前有简单介绍nodejs的一篇文章(http://www.cnblogs.com/fangsmile/p/6226044.html)

HTTP服务器

Node内建有一个模块,利用它可以很容易创建基本的HTTP服务器。请看下面案例。

my_web_server.js 

1 var http = require('http');
2 http.createServer(function (req, res) {
3   res.writeHead(200, {'Content-Type': 'text/plain'});
4   res.end('Hello World\n');
5 }).listen(8080);
6 
7 console.log('Server running on port 8080.');

在上面,我说是的基本HTTP服务器。该例中所创建的并不是一个功能全面的HTTP服务器,它并不能处理任何HTML文件、图片。事实上,无论你请求什么,它都将返回“Hello World”。你运行该代码,并在浏览器中输入“http://localhost:8080”,你将看见该文本。 

$ node my_web_server.js  

现在你可能已经注意到一些不一样的东西。你的Node.js应用并没有退出。这是因为你创建了一个服务器,你的Node.js应用将继续运行,并响应请求,直到你关闭它。

如果你希望它成为一个全功能的Web服务器,你必须检查所收到的请求,读取合适的文件,并返回所请求的内容。

首先实现一个处理静态资源的函数,其实就是对本地文件的读取操作,这个方法已满足了上面说的静态资源的处理。

 1 var http = require('http');  
 2 var fs = require("fs");
 3 http.createServer(function (req, res) {  
 4     staticResHandler("G:/nodemodule/home_index.html", "html", res)
 5 }).listen(8080);  
 6 function staticResHandler(localPath, ext, response) {
 7     fs.readFile(localPath, "binary", function (error, file) {
 8         if (error) {
 9             response.writeHead(500, { "Content-Type": "text/plain" });
10             response.end("Server Error:" + error);
11         } else {
12             response.writeHead(200, { "Content-Type": 'text/html' });
13             response.end(file, "binary");
14         }
15     });
16 }
17 console.log('Server running on port 8080.');

进一步使用nodejs创建web服务器处理get、post请求

 

path.js :

 

 

  1  var http = require('http');
  2  var fs = require('fs');
  3  var assert = require('assert');
  4  var path = require('path');
  5  var url = require('url');
  6   
  7  var config = {
  8     port:81
  9  }
 10  var sum = 0;
 11  var response = {
 12     "content":[
 13         {
 14             "type":"11111",
 15             "name":"hello world"
 16         },
 17         {
 18             "type":"22222",
 19             "name":"world Map"
 20         }
 21          
 22     ]
 23 }
 24   
 25  http.createServer(function(req,res){
 26     sum ++;
 27     var pathName = url.parse(req.url).pathname;
 28     var localPath = "";
 29     var ext = path.extname(pathName);
 30     var Type = req.method;
 31     if(Type =='POST'){
 32         var resData = {};
 33         var body = '';
 34         req.on('data',function(data){
 35             body += data;
 36             console.log('data' + data);
 37         });
 38         req.on('end',function(data){
 39             var len = body.split('&').length;
 40             if(len > 0){
 41                 for(var i=0;i<len;i++){
 42                     var key = body.split('&')[i];
 43                     resData[key.split('=')[0]] = key.split('=')[1];                         
 44                 }
 45             }
 46             res.writeHead(200,{'Content-Type':'application/x-json'});
 47             res.end(JSON.stringify(resData),'binary');  
 48         });
 49              
 50     }
 51     else if(Type =='GET'){
 52         if(pathName =='/'){
 53             pathName = '/html/index.html';
 54         }
 55         if(ext.length > 0){
 56             localPath = '.' + pathName;
 57         }
 58         else{
 59             localPath ='./src' + pathName;
 60         }
 61         console.log('localPath:' + localPath);
 62         fs.exists(localPath,function(exists){
 63             if(exists){
 64                 console.log(localPath + ' is exists');
 65                 fs.readFile(localPath,'binary',function(err,file){
 66                     if(err){
 67                         res.writeHead(500,{'Content-Type':'text/plain'});
 68                         res.end('server Error:' + err);
 69                     }
 70                     else{
 71                         res.writeHead(200,{'Content-Type':getContentTypeByExt(ext)});
 72                         if(ext === '.json'){
 73                             res.end(JSON.stringify(response),'binary');
 74                         }
 75                         else{
 76                             res.end(file,'binary');
 77                         }
 78                      
 79                     }
 80                 })
 81             }
 82             else{
 83                 res.writeHead(400,{'Content-Type':'text/plain'});
 84                 res.end('404:File Not found');
 85             }
 86          
 87          
 88     })
 89     }
 90      
 91      
 92  }).listen(config.port);
 93   
 94 function getContentTypeByExt(ext) {
 95     ext = ext.toLowerCase();
 96     if (ext === '.htm' || ext === '.html')
 97         return 'text/html';
 98     else if (ext === '.js')
 99         return 'application/x-javascript';
100     else if (ext === '.css')
101         return 'text/css';
102     else if (ext === '.jpe' || ext === '.jpeg' || ext === '.jpg')
103         return 'image/jpeg';
104     else if (ext === '.png')
105         return 'image/png';
106     else if (ext === '.ico')
107         return 'image/x-icon';
108     else if (ext === '.zip')
109         return 'application/zip';
110     else if (ext === '.doc')
111         return 'application/msword';
112     else if (ext === '.json')
113         return 'application/x-json';
114     else
115         return 'text/plain';
116 }
117   
118  console.log('new server is running: http://127.0.0.1:81')
View Code

相关文章: