Node. js 14th (route control)

Source: Internet
Author: User

ZookeeperI. Working PrincipleWhen you access the app through a browser. when a server is created in js, a simple page is displayed. In fact, it has completed a lot of transparent work. When accessing http: // localhost: 3000, the browser will send a request to the server, includes the request method, path, HTTP Protocol version, and request header information. The app parses the Request Path and calls the corresponding logic. js contains app. get ("/", routes. index) through res. render ("index", {title: "pcat"}) calls the view template index and passes the title variable. The view generates an HTML page and returns it to the browser. After the browser receives the content, it needs to obtain/stylesheets/style.css through analysis, so it will initiate a request to the server again, app. js does not have a routing rule assigned to/stylessheets/style.css, but the app uses the app. use (express. static (_ dirname + '/public') is configured with a static file server, so it is directed to the app. use the/public/stylessheets/style.css file in the directory where js is located.
This is a typical MVC Architecture. A browser sends a request, which is accepted by the route control. The browser directs the request to different servers based on different paths. The controller processes the specific request of the user and may access the objects in the database, that is, the model part generates the HTML of the view, and then the Controller returns it to the browser to complete a request.Ii. Create routing rulesWhen we access http: // localhost: 3000/octopus in a browser, the server returns the HTTP 404 error in the Response Header because/octopus is a non-existent routing rule, it is not a file in the public directory, so the response 404 assumes that we create a/octopus routing rule. App. get ('/Octopus', function (req, res ){
Res. send ('this is the octopus path ');
}); // If we define "/octopus routing rules" twice, we will follow the first defined routing rules. App. get ("/octopus", routes. octopus); // in the index. add octopus exports in js. octopus = function (req, res) {res. send ('the time is '+ new Date (). toString ();} before the server starts listening, all routing rules are set and allocated to the corresponding function when the request arrives. App. get is a function for creating routing rules. Parameter 1: Request Path parameter 2: a callback function. When the routing rule is triggered, the callback function is called and req (request information) is transmitted) and res parameters.3. Path MatchingThe preceding describes how to set routing rules for fixed paths. Express also provides more advanced Path Matching modes. 1. app. get ('/user/: username', function (req, res) {res. send ("user:" + req. params. username) ;}); Path rule/user/: username will be automatically compiled into a regular expression, similar to \/user \/([^ \/] + )\/? In this form, the path parameter can be passed through req in the corresponding function. params attribute access 2. the path rule also supports javascript regular expressions, such as: app. get (\/user \/([^ \/] + )\/?, Callback). The advantage of this is that you can define more complex path rules. Different options are that the configured parameters are anonymous. Therefore, you need to access them through req. params [0.Iv. REST-style routing rulesExpress supports REST-style requests. REST indicates state transfer. It is an HTTP-based network application interface, the HTTP method is fully used to implement unified interfaces and services. The HTTP protocol defines eight standard methods: GET: request to GET the specified resource to GET the POST: add DELETE to submit data to the specified resource: Request the server to DELETE the specified resource PUT: Request the server to store a resource update HEAD: Request the response header of the specified resource TRACE: echo the request of the server count, major users test or diagnose CONNECT: the HTTP/1.1 protocol is reserved for proxy servers that can change connections to MPs. OPTIONS: the HTTP Request Method supported by the returned server. The so-called security means that the results obtained after multiple consecutive accesses are not affected by the visitor. Power equality means that repeated requests have the same effect as one request for multiple times. For example, obtaining, updating, and deleting operations are idempotent, which is different from adding new requests. Express has designed different routing binding functions for each HTTP Request Method. For example, all the preceding functions are app. get, which indicates that the path is bound with a GET request. Other requests sent to this path will not be responded. GET app. get (path, callback) POST app. post (path, callback) PUT app. put (path, callback) DELETE app. delete (path, callback )...... all method apps. how to use all (path, callback, next? To bind a POST request, you can use the app. post (path, callback) method to set routing rules. App. all function, which supports binding all request methods to the same function, is a very flexible function.V. Control TransferExpress supports binding multiple corresponding functions app. all ('/test/: user', function (req, res, next) to the same path {// here we verify whether the user name exists. // If Direct send or call next (new Error ('user already exist') exists; // If not, call next () to give control to the next routing rule console. log ("all methods is call"); next (); res. send ('haha ');}); app. get ('/test/: user', function (req, res) {res. send ("user:" + req. pararms. user)}) but we will only return one access. Exress provides the routing control transfer method, namely the next () function. After calling, the control is handed over to the subsequent rules. 

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.