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);Running results:
##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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.