After we have created the server locally, we need to write different suffix names to access different pages of the same site, if the routing function is not implemented. Every time you visit localhost:3000 no matter what you write like Localhost:3000/index, Localhost:3000/detail ... The same address will be accessed at the end, and URL routing can be used to access different pages, and the URL module must be introduced before the URL routing function is implemented; Const URL = require (' URL '); Nodejs provides us with a URL module and provides some methods for the URL module; The final method is the parse method. You can convert a URL string to a URL object, using the following method
Const HTTP = require (' http '); Const SERVER = Http.requireserver ((req,res) =>{let urlobj = Url.parse ( Req.url);});
You can see in the control Panel that this object has a property name of pathname; This pathname can be used as a basis for judgment;
The function code to implement the route is as follows
' use strict '; Const HTTP = require (' http ');//introduce a URL module, which enables true-to-true URL routing, And there is no bug, if//need to use req.url for processing, req can decompose the req.url;//Can be used to convert the URL into an object by analogy with the parse method; Get this pathname can be the basis for judgment, jump to different pages ; Const URL = require (' URL '); Const SERVER = Http.createserver ((req, res) + = {//Console.log (Req.url); Let Realurl = '/http ' + Req.headers.host + req.url; Let Urlobj = Url.parse (Req.url); Console.info (Urlobj); let content = '; Switch (urlobj.pathname) {case '/'://home content = '
URL module with reference to Nodejs to implement URLs routing function