The server needs to perform different operations according to different URLs or requests, and we can implement this step through routing.
In the first step, we need to parse out the path of the request URL first, 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:
The code copy is as follows:
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;
OK, pathname is the path of the request, we can use it to distinguish different requests, so that we can use different codes to handle requests from /start and /upload.
Next, we will write the route and create a file called router.js, the code is as follows:
The code copy is as follows:
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;
This code does nothing, we first integrate the route and the server.
We then extend the server's start() function, run the routing function in start(), and pass the pathname to it as a parameter.
The code copy is as follows:
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:
The code copy is as follows:
var server = require("./server");
var router = require("./router");
server.start(router.route);
Run index.js and access a 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.
In the next section, we will implement different feedback for different URL requests.