This article gives you a summary of how to use routing, middleware, ge request and post request parameters in node.js. It is very detailed. Friends who need it can refer to it
1. Routing
1. What is routing
The server needs to perform different operations based on different URLs or requests. We can implement this step through routing
2. Methods to implement routing
2.1. What to do when get requests to access the URL
app.get("网址",function(req,res){ });
2.2.What to do when post requests to access the URL
app.post("网址",function(req,res){ });
2.3. Any request to access this URL
app.all("网址",function(){ });
Note: 1. The URL here is not case-sensitive, for example
app.get("/AAb",function(req,res){ //我们访问 /aab也是可以的 res.send("你好"); });
2. If you route to /a, the actual /a?id= 2&sex=nan can also be processed.
3. The use of regular expressions in routing
3.1. In regular expressions, unknown parts are grouped with parentheses, and can then be obtained using req.params[0], [1]. req.params array object.
app.get(/^\/student\/([\d]{10})$/,function(req,res){ res.send("学生信息,学号" + req.params[0]); });
3.2. Colon writing method (recommended)
var express=require('express'); var app=express(); //冒号1 app.get("/student/:id",function (req,res) { var id=req.params["id"]; //得到id的值 var reg=/^[\d]{6}$/; if(reg.test(id)){ res.send(id); }else { res.send("请检查格式"); } }); //冒号2 app.get("/:username/:oid",function(req,res){ var username = req.params["username"]; //得到username的值 var oid = req.params["oid"]; //得到//oid的值 res.write(username); res.end(oid); }); app.listen(3000);
Running results:
Colon 1:
Colon 2 :
2. Middleware
1. What is middleware
Used between applications To connect services, for example, the above get and post requests are middleware
2. The 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(); //如果没有next参数,就只会conlose出来1,而不会是1,2 }); app.get("/",function (req,res) { console.log(2); }); app.listen(3000);
2.2. Sequence conflict: The following two routes seem to have no relationship, but in fact they conflict, because admin can be used as the user name to log in or as the id
var express=require("express"); var app=express(); app.get("/:username/:id",function(req,res){ console.log("1"); res.send("用户信息" + req.params.username); }); app.get("/admin/login",function(req,res){ console.log("2"); res.send("管理员登录"); }); app.listen(3000)
Running results: When When we access 172.0.0.1:3000/admin/login, only the user information admin will be output, not the administrator login
2.3. Resolve sequence conflicts
2.3.1. Specific details go up Write, abstractly write down
var express=require("express"); var app=express(); //具体的 app.get("/admin/login",function(req,res){ console.log("2"); res.send("管理员登录"); }); //抽象的 app.get("/:username/:id",function(req,res){ console.log("1"); res.send("用户信息" + req.params.username); }); app.listen(3000)
Running results: When we access 172.0.0.1:3000/admin/login, the output is administrator login instead of user information admin
2.3.2 , Search database
var express=require("express"); var app=express(); app.get("/:username/:id",function (req,res,next) { var username=req.params.username; //检索数据库,如果username 不存在,那么next() if(检索数据库){ console.log("1"); res.send("用户信息") }else{ next(); } }); app.get("/admin/login",function (req,res) { console.log("2"); res.send("管理员登录"); }); app.listen(3000)
3. app.use() middleware: Unlike get and post, its URL is not an exact match. But it can be expanded with small folders.
3.1. Fuzzy matching of get.use()
var express=require("express"); var app=express(); //匹配所有网址 //法一 //当你不写路径的时候,实际上就相当于“/”,就是所有网址 // app.use(function (req,res,next) { // console.log(new Date()); // next(); //执行下面的 // }); //法二 app.use("/",function (req,res,next) { console.log(new Date()); next(); //执行下面的 }); //匹配/admin所有地址,例如/admin/ss/aa这个都行 app.use("/admin",function (req,res) { res.write(req.originalUrl+"\n"); // /admin/ss/aa res.write(req.path+"\n"); // /ss/aa res.write(req.baseUrl+"\n"); // /admin res.end("你好"); }); app.listen(3000);
3.2. Get.use() to read files
var express=require("express"); var fs=require("fs"); var app=express(); //当你不写路径的时候,实际上就相当于“/”,就是所有网址 app.use(haha); //haha是一个函数 app.listen(3000); // function haha(req,res) { // res.send("哈哈"); // } app.use('/admin',function (req,res) { res.send('管理员登录'); }) //根据当前的网址,读取punlic文件夹的文件 //如果有这个文件,就渲染这个文件 //如果没有这个文件,那么next() function haha(req,res,next) { var filePath=req.originalUrl; //根据当前的网址,读取public文件夹的文件 //如果有这个文件,那么渲染这个文件 //如果没哟偶这个文件,那么next(); fs.readFile("./public/"+filePath,function (err,data) { if(err){ //文件不存在 next(); //一定要写,不然处于挂起状态 return; } res.send(data.toString()); }) }
4. render and send
4.1. Quick test page of res.send() method
var express=require("express"); var app=express(); //静态服务 app.use('/jingtai',express.static("./public")); //新的路由 app.get('/images',function (req,res) { res.send("哈哈") }); //会自动识别err参数,如果有,那么就这个函数能捕获err app.use(function (req,res) { res.status(404).send("没有这个页面!"); }) app.listen(3000);
4.2. The content rendered by res.render() will be rendered according to the template file in views. If you don’t want to use the views folder and want to set the folder name yourself, then app.set("views","aaaa");
var express=require("express"); var app=express(); // //设置ejs文件夹名字 //在day3文件夹下新建文件夹a,然后在里面放ejs文件 // 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 entering 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);
Running result:
##3. Get request parameters post request parameters:
Parameters of GET request: In the URL, in Express, there is no need to use the url module. You can use the req.query object directly. POST request parameters: cannot be obtained directly in express, you must use the body-parser module. After use, you can use req.body to get the parameters. But if the form contains file upload, you still need to use the formidable module.//form.ejs <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="#" method="post"> <input type="text" name="name"/> <input type="text" name="age"/> <input type="submit"/> </form> </body> </html>
//.jsvar 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 API app.use(bodyParser.urlencoded({extended:false})); app.post('/',function (req,res) { console.log(req.body); }); app.listen(3000);
##The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
What are the methods for using ajax in Vue? How to implement data distribution slot in vue.jsHow to integrate plug-ins using Angular2 (detailed tutorial)How to flatten a javascript array?The above is the detailed content of Detailed introduction to routing and middleware in node.js. For more information, please follow other related articles on the PHP Chinese website!