NodeJS学习笔记之(Url,QueryString,Path)模块(2)


 var url = require('url');
 var qs = require('querystring');
 var path = require("path") ;
 var queryUrl = "" ;
 var root = path.basename(queryUrl) ;
 console.log(root) ; // bb?name=bigbear&memo=helloworld
 var ext = path.extname(root) ;
 console.log(ext || "Not Ext Name !") ; // Not Ext Name !


  由于api过多,以上只列出来了常用的几个,大家需认真阅读文档。

二,综合栗子

场景描述------服务器接到不同情况的请求,通过 “Url” 分别做不同处理,代码如下:

  (1),建立”index.html“  

复制代码 代码如下:


 <!doctype html>
 <html>
     <head>
         <title>Bigbear</title>
         <meta content="IE=8" http-equiv="X-UA-Compatible"/>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <style type="text/css">
             div {
                 margin-top: 50px;
                 width: 100%;
                   margin: 0px;
                 height:120px;
                 line-height:120px;
                   color:#fff;
                   font-size:22px;
                   background:#ff9900;
                 text-align: center;
             }
         </style>
         <script src="https://www.jb51.net/index.js"></script>
     </head>
     <body>
         <div>Hello,大熊!</div>
     </body>
 </html>

  (2),建立”index.js“

alert("Hello bb !") ; // 为了测试就这么一句代码
  (3),建立”server.js“

复制代码 代码如下:


var http = require("http");
var fs = require('fs');
var url = require('url');
var path = require("path") ;
http.createServer(function(request,response) {
    var method = request.method ;
    method = method.toLowerCase() ;
    var fileName = path.basename(request.url) ;
    var extName = path.extname(fileName) ;
    var root = "./" ;
    if("get" == method){
        if(extName){
            fs.readFile("./" + fileName,"utf-8",function (error,data){
                if(error)throw error ;
                response.writeHead(200,{
                    "Content-Type": {
                         ".css": "text/css" ,
                         ".js" : "application/javascript"
                  }[extName]
                }) ;
                response.write(data) ;
                response.end() ;
            });
        }
        else{
            fs.readFile(root + "index.html","utf-8",function (error,data){
                if(error)throw error ;
                response.writeHead(200,{
                    "Content-Type" : "text/html"
                });
                response.write(data) ;
                response.end() ;
            });
        }
    }
    else if("post" == request.url){
        // handle post here
    }
}).listen(8888) ;
console.log("Web Server Running , Port On ---> 8888") ;


 
  node server.js 运行一下。

三,总结一下

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxzzw.html