路由:路径由来。
为路由提供请求的 URL 和其他需要的 GET 及 POST 参数,随后路由需要根据这些数据来执行相应的代码。
因此,我们需要查看 HTTP 请求,从中提取出请求的 URL 以及 GET/POST 参数。
我们需要的所有数据都会包含在 request 对象中,该对象作为 onRequest() 回调函数的第一个参数传递。但是为了解析这些数据,我们需要额外的 Node.JS 模块,它们分别是 url 和 querystring 模块。
在我们所要构建的应用中,这意味着来自 /start 和 /upload 的请求可以使用不同的代码来处理。稍后我们将看到这些内容是如何整合到一起的。
编写路由了,建立一个名为 router.js 的文件:
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;
扩展一下服务器的 start() 函数,以便将路由函数作为参数传递过去,server.js 文件代码如下:
//服务器//路由处理需要引入http和url模块
var http = require("http");
var url = require("url");
function start(route) {
console.log("route:"+route); //请求函数request参数,response响应参数
function onRequest(request, response) {
//url parse解析
var pathname = url.parse(request.url).pathname;
console.log("pathname:" + pathname);
//扔给路由处理
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公共接口,供其他模块引用
exports.start = start;
扩展 index.js,使得路由函数可以被注入到服务器中:
var server = require("./server");
var router = require("./router");
server.start(router.route);
启动应用(node index.js),随后请求一个URL,HTTP服务器已经在使用路由模块了,并会将请求的路径传递给路由:浏览器访问 http://127.0.0.1:8888/,输出结果如下
route:function route(pathname) { console.log("About to route a request for " + pathname); }
Server has started.
pathname:/
About to route a request for /
pathname:/favicon.ico
About to route a request for /favicon.ico
网友评论