URL module with reference to Nodejs to implement URLs routing function

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.