The server needs to perform different operations based on different URLs or requests. We can implement this step through routing.
In the first step, we need to parse out the path of the request URL, and we introduce the url module.
Let’s add some logic to the onRequest() function to find out the URL path requested by the browser:
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的请求使用不同的代码来处理。
Then let’s write the route and create a router called router. js file, the code is as follows:
function route(pathname) { console.log("About to route a request for " + pathname); } exports.route = route;
This code does nothing. Let’s integrate the routing and server first.
We then extend the server's start() function, run the routing function in start(), and pass pathname to it as a parameter.
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;
At the same time, we will extend index.js accordingly so that the routing function can be injected into the server:
var server = require("./server"); var router = require("./router"); server.start(router.route);
Run index.js and access any path, such as / upload, you will find the console output, About to route a request for /upload.
This means that our HTTP server and request routing module can already communicate with each other.
The above is the entire content of this chapter. For more related tutorials, please visit Node.js Video Tutorial!