1. How Routing control works
Code in the Routes/index.js
When accessing the home page, call the Ejs template engine, render the Index.ejs template file, generate a static page, and display it in the browser.
function (req, res) { // capture GET request to access home page res.render (' index ', {title: ' Express ' });
The official notation is to implement a simple routing assignment in App.js, and then to find the corresponding route function in the Index.js, and finally implement the routing function.
We might as well put the routing controller and the functions that implement the routing function into the index.js, there is only one total routing interface in the app.js.
Modified App.js
1 //load Express, Path module via require (). And the index.js and User.js routing files under the Routes folder2 varExpress = require (' Express ');3 varPath = require (' path ');4 varFavicon = require (' Serve-favicon '));5 varLogger = require (' Morgan ');6 varCookieparser = require (' Cookie-parser '));7 varBodyparser = require (' Body-parser '));8 //load a routing file9 varRoutes = require ('./routes/index '));Ten varUsers = require ('./routes/users ')); One A varApp = Express ();//generate an Express instance app - app.set (' Port ', process.env.port| | 3000); // The first chapter adds the //View engine Setup -App.set (' Views ', Path.join (__dirname, ' views '));//set the Views folder to the directory where the view files reside, that is, where the template files are stored, __dirname is a global variable, and the directory where the script currently executing is stored. -App.set (' View engine ', ' Ejs ');//set the view template engine to Ejs - + //uncomment after placing your favicon in/public - //App.use (Favicon (__dirname + '/public/favicon.ico ')); Set/public/favicon.ico to Favicon icon +App.use (Logger (' dev '));//Load Log Middleware AApp.use (Bodyparser.json ());//loading middleware for parsing JSON atApp.use (bodyparser.urlencoded ({extended:false}));//loading middleware for parsing urlencoded request Body -App.use (Cookieparser ());//loading middleware for parsing cookies -App.use (Express.static (Path.join (__dirname, ' public '));//set the public folder to a directory where static files are stored - //// Routing Controller chapter I limitation of //app.use ('/', routes); //app.use ('/users ', users); - The First chapter adds the routes (app); App.listen (app.get (' Port '),function() { console.log (' Express server Listening on port ' + app.get (' Port '); }); $Panax Notoginseng //catch 404 and forward to error handler catch a 404 error and forward to the error handler. -App.use (function(req, res, next) { the varErr =NewError (' Not Found '); +Err.status = 404; A Next (err); the }); + - //Error Handlers $ $ //Development Error Handler - //Would print StackTrace - //the error handler in the development environment renders the error message and displays it in the browser. the if(App.get (' env ') = = = ' Development ') { -App.use (function(Err, req, res, next) {WuyiRes.status (Err.status | | 500); theRes.render (' ERROR ', { - Message:err.message, Wu Error:err - }); About }); $ } - - //Production Error Handler - //no stacktraces leaked to user A //The error handler in the production environment renders the error message and displays it in the browser. +App.use (function(Err, req, res, next) { theRes.status (Err.status | | 500); -Res.render (' ERROR ', { $ Message:err.message, the error: {} the }); the }); the - //module.exports = app;//Export the app instance and use it for other modules
Index.js
1 //var express = require (' Express ');2 //var router = Express. Router (); Create a route instance3 //4 /// * GET home page. * /5 //router.get ('/', function (req, res) {//Capture GET request to access home page6 //res.render (' index ', {title: ' Express '});7 //});8 //9 //module.exports = router;//export route and load in app with App.use ('/', routes)Ten One AModule.exports =function(APP) { -App.get ('/',function(req,res) { -Res.render (' index ', {title: ' Express '}); the }); -App.get ('/test ',function(req,res) { -Res.send (' Hello world! '); - }) +};
2. Routing rules
Express encapsulates a variety of HTTP request methods, primarily using
app.get()
and app.post()
The first parameter is the requested path, and the second parameter is a callback function (including the Req and res two parameters that represent the request and response information, respectively).
App.get (* *,function(req,res) {* *}); App.post (* *,function(req,res) { ***});
Path requests and corresponding fetch paths are available in the following ways:
req.query
: Processing get requests, getting GET request parameters
req.params
: Handles get or post requests in/:xxx form, gets request parameters
req.body
: Process POST request, get POST request body
req.param()
: Handles get and post requests, but finds priority from high to low to Req.params→req.body→req.query
3. Add a Routing rule
The browser opens http://localhost:3000/back to the "Welcome to Express" interface
Open Http://localhost:3000/test, return to "404 Not Found"
At this point, add the route:
In Index.js, add the response as follows:
After you open http://localhost:3000/test, you can return to the "Hello world! "Interface.
"Above test, read the effect also reply to the original code"
4. Template Rendering Ejs
// __dirname+ '/views ' is the directory where the view files are stored app.set (' views ', __dirname +'/views '// set template engine for Ejs App.set (' View engine ', ' Ejs ');
The Ejs label system is very simple and it has only the following three types of labels:
- <% Code%>:javascript codes.
- <%= code%>: Displays content that has been replaced with HTML special characters.
- <%-code%>: Displays the original HTML content.
Instead of using layout for page layouts, we use the more simple and flexible include. The simple use of include is as follows:
<%- include a %>hello,world!<%- include b %>
"My notes BLOG3" express basic usage, and routing control, and template rendering Ejs