您的位置:首页 > Web前端 > Node.js

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: