nodejs基础 -- 路由
2015-12-18 10:51
591 查看
我们要为路由提供请求的URL和其他需要的GET/POST参数,随后路由需要根据这些数据(URL、GET/POST参数)来执行相应的代码。
因此,需要查看HTTP请求,从中提取出请求的URL及GET/POST参数。(这一功能属于路由还是服务器?暂无定论,这里暂定为HTTP服务器的功能)。这些数据(url,get/post参数)都包含在request对象中,而该对象是作为onRequest()回调函数的第一个参数传递的。
总结以上:
首先,我们需要查看HTTP请求,从中提取出URL及GET/POST参数,然后路由就可以根据这些残血来执行相应的代码。
示例:
1、创建server.js服务器文件,内容如下:
2、建立router.js路由文件,内容如下:
3、建立调用入口文件index.js,内容如下:
运行index.js文件,结果如下:
因此,需要查看HTTP请求,从中提取出请求的URL及GET/POST参数。(这一功能属于路由还是服务器?暂无定论,这里暂定为HTTP服务器的功能)。这些数据(url,get/post参数)都包含在request对象中,而该对象是作为onRequest()回调函数的第一个参数传递的。
总结以上:
首先,我们需要查看HTTP请求,从中提取出URL及GET/POST参数,然后路由就可以根据这些残血来执行相应的代码。
示例:
1、创建server.js服务器文件,内容如下:
var http = require("http"); var url = require("url"); //引入url原生模块,用来解析request中带的url及get/post参数 function start(route){ function onRequest(request,response){ var pathname = url.parse(request.url).pathname; //通过url对象解析路径 console.log("Request for"+pathname+"received."); route(pathname); response.writeHead(200,{"content-type":"text/plain"}); response.write("hello world"); response.end(); } http.createServer(onRequest).listen(8888); console.log("server has started..."); } exports.start = start;
2、建立router.js路由文件,内容如下:
function route(pathname){ console.log("about to route a request for"+pathname); } exports.route = route;
3、建立调用入口文件index.js,内容如下:
var server = require("./server"); var router = require("./router"); server.start(router.route);
运行index.js文件,结果如下:
相关文章推荐
- 【Nodejs】windows下node.js安装教程图文详解
- 如何在不影响hadoop集群正常运行的情况下迁移主控节点[namenode]
- 使用 AngularJS & NodeJS 实现基于token 的认证应用(转)
- LeetCode OJ:Reverse Nodes in k-Group(K个K个的分割节点)
- leetcode19---Remove Nth Node From End of List
- (java)Remove Nth Node From End of List
- nodejs webstorm
- Hadoop的datanode,namenode无法启动
- 用Node完成AWS S3的Upload流程之全世界最简版
- NODEJS 初学示例
- 117 Populating Next Right Pointers in Each Node II
- Node.js 的Web server--Fenix
- Nodejs源码分析之assert
- Populating Next Right Pointers in Each Node,Populating Next Right Pointers in Each Node II
- NodeManagerMetrics上精确化Container指标监控
- node.js之socket.io模块
- HDFS源码分析(一)-----INode文件节点
- hive日志位置(日志定位报错:Failed with exception Unable to move sourcehdfs://namenode/tmp/hive-pmp_bi/h)
- hive日志位置(日志定位报错:Failed with exception Unable to move sourcehdfs://namenode/tmp/hive-pmp_bi/h)
- nodejs基础 -- 函数