Home > Web Front-end > JS Tutorial > Create nodejs server easily (4): Routing

Create nodejs server easily (4): Routing

PHPz
Release: 2018-09-30 09:59:44
Original
1270 people have browsed it

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的请求使用不同的代码来处理。
Copy after login

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;
Copy after login

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;
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template