nodejs进阶3-路由处理
发布时间:2017年01月04日作者:文章转自网络,版权归原作者所有,反馈可立刻删除
1. 路由选择过程
处理不同的HTTP请求在我们的代码中是一个不同的部分,叫做“路由选择”。
那么,我们接下来就创造一个叫做 路由 的模块吧。我们需要查看HTTP请求,从中提取出请求的URL以及GET/POST参数。
url.parse(string).query
|
url.parse(string).pathname |
| |
| |
------ -------------------
http://localhost:8888/start?foo=bar&hello=world
--- -----
| |
| |
querystring(string)["foo"] |
|
querystring(string)["hello"]
2. 路由选择实现代码
新建属于服务器端的路由文件router.js
复制代码
1 //-----------------router.js--------------------------------
2 module.exports={
3 login:function(req,res){
4 res.write("我是login方法");
5 },
6 register:function(req,res){
7 res.write("我是注册方法");
8 }
9 }
复制代码
服务端调用路由,方式和上一节课《nodejs进阶2--函数模块调用》中最后提到的字符串调用函数一样。
复制代码
1 //---------4_router.js-----------
2 var http = require('http');
3 var url = require('url');
4 var router = require('./router');
5 http.createServer(function (request, response) {
6 response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
7 if(request.url!=="/favicon.ico"){
8 var pathname = url.parse(request.url).pathname;//得到请求的路径
9 console.log(pathname);
10 pathname = pathname.replace(/\//, '');//替换掉前面的/
11 console.log(pathname);
12 router[pathname](request,response);
13 response.end('');
14 }
15 }).listen(8000);
16 console.log('Server running at http://127.0.0.1:8000/');
复制代码
上面我们用到了node自带模块url。url.path(urlStr):将一个URL字符串转换成对象并返回。
3. url.path(urlStr)实例
下面展示两个url.parse的实例
例1. url.parse('http://stackoverflow.com/questions/17184791').pathname
结果为:"/questions/17184791"
例2:
复制代码
1 var url = require('url');
2 var a = url.parse('http://example.com:8080/one?a=index&t=article&m=default');
3 console.log(a);
4
5 //输出结果:
6 {
7 protocol : 'http' ,
8 auth : null ,
9 host : 'example.com:8080' ,
10 port : '8080' ,
11 hostname : 'example.com' ,
12 hash : null ,
13 search : '?a=index&t=article&m=default',
14 query : 'a=index&t=article&m=default',
15 pathname : '/one',
16 path : '/one?a=index&t

