1. url.parse(url)解析

该方法将一个URL字符串转换成对象并返回。

url.parse(urlStr, [parseQueryString], [slashesDenoteHost])

接收参数:

urlStr                                       url字符串

parseQueryString                   为true时将使用查询模块分析查询字符串,默认为false

我们通过解析HTTP请求,从中提取出请求的URL以及GET/POST参数。url是nodejs内置的一个模板,我们需要require("url")获取,下面的url:http://localhost:8888/start?foo=bar&hello=world,通过url.parse解析出的一个对象的各个字段名对应url的各部分。

var url = require('url');
var queryUrl = "http://localhost:8888/start?foo=bar&hello=world" ;
console.log(typeof url.parse(queryUrl)) ;
console.log(url.parse(queryUrl)) ;
//输出结果如下:
/* object // typeof
{
protocol: 'http:',
slashes: true,
auth: null,
host: 'localhost:8888',
port: '8888',
hostname: 'localhost',
hash: null,
search: '?foo=bar&hello=world',
query: 'foo=bar&hello=world',
pathname: '/start',
path: '/start?foo=bar&hello=world',
href: 'http://localhost:8888/start?foo=bar&hello=world'
} 加以说明如下:  
  protocol: 请求协议
  host: URL主机名已全部转换成小写, 包括端口信息
  auth:URL中身份验证信息部分
  hostname:主机的主机名部分, 已转换成小写
  port: 主机的端口号部分
  pathname: URL的路径部分,位于主机名之后请求查询之前
  search: URL 的“查询字符串”部分,包括开头的问号。
  path: pathname 和 search 连在一起。
  query: 查询字符串中的参数部分(问号后面部分字符串),或者使用 querystring.parse() 解析后返回的对象。
  hash: URL 的 “#” 后面部分(包括 # 符号) */

用下面的图更形象的描述说明给大家:

                               url.parse(string).query
|
url.parse(string).pathname |
| |
| |
------ -------------------
http://localhost:8888/start?foo=bar&hello=world
--- -----
| |
| |
querystring(string)["foo"] |
|
querystring(string)["hello"]

2. 路由选择实现代码

处理不同的HTTP请求在我们的代码中是另外一个不同的部分,叫做“路由选择”。

那么,我们接下来就创造一个叫做 路由 的模块吧。

新建属于服务器端的路由文件router.js

 //-----------------router.js--------------------------------
module.exports={
    login:function(req,res){
        res.write("我是login方法");
    },
register:function(req,res){
        res.write("我是注册方法");
    }
}

服务端调用路由,方式和上一节课《nodejs进阶2--函数模块调用》中最后提到的字符串调用函数一样。

 //---------4_router.js-----------
var http = require('http');
var url = require('url');
var router = require('./router');
http.createServer(function    (request,    response)    {
        response.writeHead(200,    {'Content-Type': 'text/html; charset=utf-8'});
        if(request.url!=="/favicon.ico"){
                var pathname = url.parse(request.url).pathname;//得到请求的路径
         console.log(pathname);
                pathname = pathname.replace(/\//, '');//替换掉前面的/
         console.log(pathname);
         router[pathname](request,response);
                response.end('');
        }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');    

上面我们用到了node自带模块url。url.path(urlStr):将一个URL字符串转换成对象并返回。

3. 向页面输出html文件

对于一般的get请求,例如localhost/login 我们需要给浏览器输出个页面login.html,那我们怎么做呢?

首先我们新增两个页面

1.login.html

 <html>
<head>
</head>
<body>
登录:
<p>这是一个段落</p>
<h1>样式1</h1>
</body>
<html>

2.register.html

 <html>
<head>
</head>
<body>
注册:
<p>这是一个段落</p>
<h1>样式1</h1>
</body>
<html>

读取文件的方法,我们放到文件models/file.js里

 //-------------models/file.js-------------------------
var  fs=  require('fs');
module.exports={
    readfile:function(path,callback){          //异步读文件,需要传入回调函数
        fs.readFile(path,  function  (err,  data)  {
            if  (err)  {
               console.log(err);
            }else{
callback(data);
            }
        });
        console.log("异步方法执行完毕");
    },
    readfileSync:function(path){      //同步读取
        var  data  =  fs.readFileSync(path,'utf-8');
        console.log("同步方法执行完毕");
        return  data;                
    }
}

router.js需要调用文件读取方法,把两个页面html文件读取出内容并输出到response。需要注意的是:res.end()这句话的位置,如果用异步读文件的方法就不能放到server创建那块了

 //-----------------router.js--------------------------------
var file = require('./models/file');
module.exports={
    login:function(req,res){
var callback=function(data){
res.write(data);
res.end();
}
file.readfile('./views/login.html',callback);//使用异步读取
    },
register:function(req,res){
        var data=file.readfileSync('./views/register.html');//使用同步读取
res.write(data);
res.end();
    }
}

我们重新运行:node 4_router.js。分别在浏览器输入http://localhost:8000/login 和http://localhost:8000/register  ,输出了login.html和register.html页面的内容。

最新文章

  1. ASP.NET MVC5+EF6+EasyUI 后台管理系统(7)-MVC与EasyUI DataGrid
  2. 【MongoDB初识】-其他操作
  3. CentOS7.2部署OpenStack(一)—环境准备
  4. spring启动component-scan类扫描加载过程---源码分析
  5. Session与cookie的区别?
  6. Python数据分析之numpy学习
  7. 【PHP】$_POST, $HTTP_RAW_POST_DATA, and php://input
  8. WCF 入门 (17)
  9. ajaxFileUpload用法
  10. C#实现远程机器管理
  11. gettype
  12. C语言程序设计第二次作业—————顺序结构
  13. Android进程通信之一:两种序列化方式
  14. Maven web 项目工程的建立
  15. AjaxHandler
  16. sql数据查询基础笔记
  17. CustomJSProperties珍藏版。目的是减少客户端的代码数量,但是又能将服务器数据传输给客户端。关键是:数据是实时更新的!!!!
  18. Leetcode 题解 First Missing Positive
  19. 【分享】熟练的Java程序员应该掌握哪些技术?
  20. linux如何查看端口被哪个进程占用?

热门文章

  1. Unity3d入门 - 关于unity工具的熟悉
  2. 如何一步一步用DDD设计一个电商网站(七)—— 实现售价上下文
  3. Xcode模拟器启动不了,修复ios模拟器
  4. Android业务组件化之子模块SubModule的拆分以及它们之间的路由Router实现
  5. MementoPattern(备忘录模式)
  6. CSS3 @keyframes 动画
  7. Atitit &#160;godaddy 文件权限 root权限设置
  8. 图解DevExpress RichEditControl富文本的使用,附源码及官方API
  9. 嵌入式C语言代码的调试技巧
  10. javaMail