zoukankan      html  css  js  c++  java
  • nodejs创建http服务器

    之前有简单介绍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
    ');
    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

     

     index.html 

    <html>
    <head>
    <title>Sample Page</title>
     <meta charset="UTF-8">
    </head>
    <link rel="stylesheet" href="../css/index.css"/>
    <body>
    Hello World!
    <div class="music_class">
        <img src="../img/music_class.png" alt="分类图片"/>
    </div>
    <div>
        <div>get请求获取的数据:</div>
        <ul class="music_category_list">
        </ul>
    </div>
    <div>
        <button class='postClick'>点击POST请求</button>
        <div class='postDiv'>
            <span>post请求获取的数据:</span>
            <span class='postData'></span>
        </div>
    </div>
    </body>
    <script src="../js/lib/jquery-1.11.3.min.js"></script>
    <script src="../js/page/index.js"></script>
    </html>

     index.js 

     1 $(document).ready(function(){
     2     function createEle(){
     3         var img = new Image();
     4         img.src = "../img/music_hot.png";
     5         img.onload = function(){
     6             var imgDom = '<img src="../img/music_hot.png"/>';
     7             $('.music_class').append(imgDom);
     8         }   
     9     }
    10     createEle();
    11     (function getDate(){
    12         var XHR = $.ajax({
    13                 timeout : 20000,
    14                 dataType : 'json',
    15                 type : 'GET',
    16                 url : '../package.json',
    17                 data : '',
    18                 beforeSend : function (request) {
    19                     request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
    20                 },
    21                 complete : function(XMLHttpRequest, status) {
    22                     if (status == 'timeout') {
    23                         //theUIApp.tip($("body"), "网络异常,请检查网络");
    24                         util.toast("网络异常,请检查网络");
    25                     }
    26                 },
    27                 success : function (result) {
    28                     var LiLength = result.content.length;
    29                     if(LiLength > 0){
    30                         for(var i=0;i<LiLength;i++){
    31                             var inp = '<li>' + result.content[i].name + '</li>';
    32                             $('.music_category_list').append(inp);
    33                         }
    34                     }                   
    35                 },
    36                 error : function (result) {
    37                     console.log(result)
    38                 }               
    39             });
    40     })();
    41      
    42     $('.postClick').click(function(){
    43         Post();
    44     })
    45      
    46     function Post(){
    47         var option = {
    48             name:'zhangsan',
    49             age:'15'
    50         }
    51         var XHR = $.ajax({
    52             timeout : 20000,
    53             dataType : 'json',
    54             type : 'POST',
    55             url : '../package.json',
    56             data : option,
    57             beforeSend : function (request) {
    58                 request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
    59             },
    60             complete : function(XMLHttpRequest, status) {
    61                 if (status == 'timeout') {
    62                     //theUIApp.tip($("body"), "网络异常,请检查网络");
    63                     util.toast("网络异常,请检查网络");
    64                 }
    65             },
    66             success : function (result) {
    67                 if(result){
    68                     $('.postData').text(result.name);
    69                 }                   
    70             },
    71             error : function (result) {
    72                 console.log(result)
    73             }               
    74         });
    75     }
    76 })
    View Code

    index.css 

     1 @charset "utf-8";
     2 html{ height: 100%}
     3 body{
     4     font-family:"Microsoft YaHei",Arial,Helvetica,sans-serif,"宋体";
     5     font-size:3.5rem;
     6 }
     7 li{
     8     list-style-type:none;
     9 }
    10 .music_class{
    11     width:100%;
    12     margin:10px;
    13 }
    14 .music_class img{
    15     width:95%;
    16 }
    17 .music_category_list{
    18     margin:10px;
    19 }
    20 .music_category_list li{
    21     width:95%;
    22     margin:5px;
    23     padding:5px;
    24     border:2px solid #ccc;
    25 }
    26 .postData{
    27     width:100%;
    28     color:blue;
    29     fonst-size:20px;
    30     text-align:center;
    31 }
    32 button{
    33     font-size:30px;
    34     width:300px;
    35     height:100px;
    36 }
    View Code

     建议服务器的相关代码下载地址:http://files.cnblogs.com/files/fangsmile/nodejs-http%E6%9C%8D%E5%8A%A1%E5%99%A8.zip

     下载下来运行:node path    然后访问 http://127.0.0.1:81/index.html

  • 相关阅读:
    构造函数析构函数为什么没有返回值?
    std::tr1::shared_ptr 使用的一点体会
    C++完美实现Singleton模式
    为什么C++中空类和空结构体大小为1?
    同时判断CPU是大端还是小端完全实现
    优先级反转
    linux sed 批量替换字符串
    禁掉Apache web server签名 How to turn off server signature on Apache web server
    Python中用format函数格式化字符串的用法
    Eclipse (indigo) 中安装jdk包并运行Maven
  • 原文地址:https://www.cnblogs.com/fangsmile/p/6226963.html
Copyright © 2011-2022 走看看