One, routing
1. What is routing
The server needs to perform a different operation depending on the URL or request, and we can implement this step by routing
2. How to implement Routing
2.1, GET request to access the URL, what to do
1 app.get ("url",function(req,res) {2 3 });
2.2, when the POST request to visit the URL, what to do
1 app.post ("url",function(req,res) {2 3 });
2.3. Any request to visit this website
1 app.all ("url",function() {2 3 });
Note: 1, ' The URLs here are not case-sensitive, for example
1 app.get ("/aab",function(req,res) {//We visit/aab is also possible 2 res.send ("Hello"); 3 });
2, you route to/A, the actual/a?id=2&sex=nan can also be processed.
3, the use of the expression in the route
3.1. In regular expressions, the unknown part is grouped with parentheses and can then be obtained using req.params[0], [1]. The Req.params class array object.
1 app.get (/^\/student\/([\d]{10}) $/,function(req,res) {2 res.send ("Student information, study number" + Req.params[0]); 3 });
3.2. Colon notation (recommended)
varExpress=require (' Express ');varapp=Express ();//Colon 1App.get ("/student/:id",function(req,res) {varId=req.params["id"]; Get the value of IDvarreg=/^[\d]{6}$/; if(Reg.test (id)) {res.send (id)); }Else{res.send ("Please check the format"); }});//Colon 2App.get ("/:username/:oid",function(req,res) {varUsername =req.params["username"]; Get the value of usernamevarOID =req.params["OID"]; Get the value of//oid res.write (username); Res.end (OID);}); App.listen (3000);
Operation Result:
Colon 1:
Colon 2:
Second, the middleware
1. What is middleware
Applied to the application to act as a connection service, such as the GET, POST request above is the middleware
2. Order of all routes (middleware) in Express (very important)
2.1. Next () method
var express=require ("Express"); var app=Express (); App.get ("/",function (req,res,next) { console.log (1 ); Next (); // If there is no next argument, it will only conlose out 1, not }); App.get ("/",function (req,res) { Console.log (2);}); App.listen ( 3000);
2.2, Sequence conflict: The following two routes, it does not seem to have a relationship, but in fact there is a conflict, because the admin can be used as the user name login can be used as ID
var express=require ("Express"); var app=Express (); App.get ("/: Username/: ID",function(req,res) { Console.log ("1"); Res.send ("User Information" + Req.params.username);}); App.get ("/admin/login",function(req,res) { Console.log (" 2 "); Res.send ("Administrator Login");}); App.listen (3000)
Run Result: When we visit 172.0.0.1:3000/admin/login, we only output the user Information admin and not the administrator login
2.3. Resolving sequence conflicts
2.3.1, specific to write, abstract down
var express=require ("Express"); var app=Express (); // specific app.get ("/admin/login",function(req,res) { console.log ("2"); Res.send ("Administrator Login");}); // abstract app.get ("/:username/:id",function(req,res) { console.log ("1"); Res.send ("User Information" + Req.params.username);}); App.listen (3000)
Run Result: Output Administrator login When we access 172.0.0.1:3000/admin/login and not user Information admin
2.3.2, retrieving databases
varExpress=require ("Express");varapp=Express (); App.get ("/:username/:id",function(req,res,next) {varUsername=Req.params.username; Retrieves the database, if username does not exist, then next ()if(Retrieve database) {Console.log ("1"); Res.send ("User Information") }Else{next (); }}); App.get ("/admin/login",function(req,res) {Console.log ("2"); Res.send ("Administrator Login");}); App.listen (3000)
3, App.use () middleware: Unlike Get, post, his URL is not exactly matched . It can be expanded with small folders.
3.1. Fuzzy matching of Get.use ()
varExpress=require ("Express");varapp=Express ();//Match all URLs//fa Yi//when you do not write the path, it is actually the equivalent of "/", that is, all the URLs//app.use (function (req,res,next) {//Console.log (New Date ());//next (); Perform the following// });//Method TwoApp.use ("/",function(Req,res,next) {Console.log (NewDate ()); Next (); //perform the following});//match/admin All addresses, such as/ADMIN/SS/AA.App.use ("/admin",function(req,res) {res.write (Req.originalurl+ "\ n");///ADMIN/SS/AARes.write (req.path+ "\ n");///SS/AARes.write (req.baseurl+ "\ n");///adminRes.end ("Hello");}); App.listen (3000);
3.2, Get.use () read the file
varExpress=require ("Express");varFs=require ("FS");varapp=Express ();//when you do not write the path, it is actually the equivalent of "/", that is, all the URLsApp.use (haha);//haha is a functionApp.listen (3000);//function haha (req,res) {//res.send ("haha");// }App.use ('/admin ',function(req,res) {res.send (' Admin login ');})//read the file of the Punlic folder according to the current URL//If you have this file, render this file//If you do not have this file, then next ()functionhaha (req,res,next) {varFilepath=Req.originalurl; //read the files of the public folder according to the current URL //If you have this file, then render this file //If you don't have this file, then next ();Fs.readfile ("./public/" +filepath,function(err,data) {if(err) {//file does not existNext ();//be sure to write or be in a pending state return; } res.send (Data.tostring ()); })}
4. Render and send
4.1. Res.send () Method Quick test Page
var express=require ("Express"); var app=Express (); // Static service app.use ('/jingtai ', express.static ("./public")); // New Route app.get ('/images ',function (req,res) { res.send ("haha")}); // The err parameter is automatically recognized, and if so, the function can catch the Errapp.use ( req,res) { res.status (404). Send ("No this page!") ");}) App.listen (3000);
4.2, Res.render () rendering content, will be based on the template file in the views rendered. If you do not want to use the Views folder, you want to set the folder name, then App.set ("views", "AAAA");
var express=require ("Express"); var app=Express (); // //Set Ejs folder name //Create a new folder under the Day3 folder, then put the Ejs file // app.set ("views", "a")App.set ("View") Engine "," Ejs "), App.get ("/",function(req,res) { res.render (" haha ", {News :[]});}); App.get ("/check",function (req,res) { res.send ({ "user": "OK" })} ) App.listen (3000);
5, Req.query: when the input http://127.0.0.1:3000/?id=0&ag=9
var express=require ("Express"); var app=Express (); App.get ("/",function (req,res) { console.log (req.query); Res.send ();}); App.listen (3000);
Operation Result:
Three, GET request parameters POST request parameters:
Get request parameters: In the URL, in Express, you do not need to use the URL module. You can use the Req.query object directly.
Post request parameters: Not available directly in Express, you must use the Body-parser module. After use, the parameters can be obtained with req.body. However, if the form contains file uploads, you still need to use the formidable module.
// form.ejs<!doctype html>
. js
var express=require ("Express"); var bodyparser=require (' Body-parser '); var app=Express (), App.set (' view engine ', ' Ejs ') app.get ('/',function (req, RES) { res.render ("form");}); // bodyparser APIapp.use (bodyparser.urlencoded ({extended:false})); App.post ('/', function (req,res) { console.log (req.body);}); App.listen (3000);
Operation Result:
How to question welcome advice!
node. js routing, middleware, GE request and POST request parameters