nodejs 路由
2016-06-21 15:05
411 查看
http 请求的所有数据都会包含在 request 对象中,该对象作为 onRequest() 回调函数的第一个参数传递。但是为了解析这些数据,还需要 url 和 querystring 模块
url.parse(string).query
url.parse(string).pathname
http://localhost:8888/start?foo=bar&hello=world
querystring(string)["foo"]
例子:
我们首先创建一个 router 来获取路由信息:
function route(pathname){
console.log("About to route a request for "+ pathname);
}
exports.route = route;
其中的 route 是暴露出去的 route 函数
然后创建一个 server 并且分析 url 信息:
var http = require("http");
var url = require("url");
function start(route){
function onRequest(request, response){
var pathname = url.parse(request.url).pathname;
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;
可以看到 onRequest 回调函数中 request 参数,对其中的数据进行分析
最后定义一个 index.js 去调用 server 中的start 来分析 url 数据
var server = require("./server");
var router = require("./router");
server.start(router.route);
url.parse(string).query
url.parse(string).pathname
http://localhost:8888/start?foo=bar&hello=world
querystring(string)["foo"]
例子:
我们首先创建一个 router 来获取路由信息:
function route(pathname){
console.log("About to route a request for "+ pathname);
}
exports.route = route;
其中的 route 是暴露出去的 route 函数
然后创建一个 server 并且分析 url 信息:
var http = require("http");
var url = require("url");
function start(route){
function onRequest(request, response){
var pathname = url.parse(request.url).pathname;
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;
可以看到 onRequest 回调函数中 request 参数,对其中的数据进行分析
最后定义一个 index.js 去调用 server 中的start 来分析 url 数据
var server = require("./server");
var router = require("./router");
server.start(router.route);
相关文章推荐
- nodejs 函数
- nodejs 事件
- nodejs 模块系统
- 安装 node
- hibernate 中,出现了错误 "node to traverse cannot be null!" 如何改正
- (转)nodejs中npm常用命令
- LeetCode Reverse Nodes in k-Group(单链表连续分段反转)
- ROS学习--人脸识别NODE
- JetBrains使用技能分享征集大赛优秀作品——用webstorm开发NodeJS项目
- ROS学习--语义理解NODE(NLU,NLP)
- systemtap [主设备号,次设备好,inode]监控文件
- LeetCode OJ | #25 Reverse Nodes in k-Group
- nodejs的require模块及路径
- Nodejs的测试和测试驱动开发
- Node.js模块定义总结
- node环境
- node应用线上部署时锁定包的依赖版本
- Nodejs与Python脚本语言混编
- when 让你跳出异步回调噩梦 node.js下promise/A规范的使用
- node.js 下使用 util.inherits 来实现继承