Home  >  Article  >  Web Front-end  >  轻松创建nodejs服务器(4):路由

轻松创建nodejs服务器(4):路由

PHPz
PHPzOriginal
2016-05-16 16:25:511213browse

服务器需要根据不同的URL或请求来执行不一样的操作,我们可以通过路由来实现这个步骤。

第一步我们需要先解析出请求URL的路径,我们引入url模块。

我们来给onRequest()函数加上一些逻辑,用来找出浏览器请求的URL路径:

var http = require("http");
var url = require("url");
function start() {
 function onRequest(request, response) {
  var pathname = url.parse(request.url).pathname;
  console.log("Request for " + pathname + " received.");
  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;好了,pathname就是请求的路径,我们可以用它来区别不同请求了,这样一来我们就可以对来自/start和/upload的请求使用不同的代码来处理。

接着我们来编写路由,建立一个名为router.js的文件,代码如下:

function route(pathname) {
 console.log("About to route a request for " + pathname);
}
exports.route = route;

这段代码什么都没干,我们先把路由和服务器整合起来。

我们接着扩展服务器的start()函数,在start()中运行路由函数,并将pathname作为参数传给它。

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;

同时,我们会相应扩展index.js,使得路由函数可以被注入到服务器中:

var server = require("./server");
var router = require("./router");
server.start(router.route);

运行index.js,随便访问个路径,比如/upload,就会发现控制台输出,About to route a request for /upload.

这就意味着我们的HTTP服务器和请求路由模块已经可以相互交流了。

以上就是本章的全部内容,更多相关教程请访问Node.js视频教程

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn