Home Web Front-end JS Tutorial Detailed introduction to routing and middleware in node.js

Detailed introduction to routing and middleware in node.js

Jun 15, 2018 pm 02:41 PM
nodejs middleware

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){
  
 });
Copy after login

 2.2.What to do when post requests to access the URL

 app.post("网址",function(req,res){
  
 });
Copy after login

2.3. Any request to access this URL

 app.all("网址",function(){
  
 });
Copy after login

Note: 1. The URL here is not case-sensitive, for example

 app.get("/AAb",function(req,res){        //我们访问  /aab也是可以的
  res.send("你好");
 });
Copy after login

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]);
 });
Copy after login

  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);
Copy after login

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);
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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);
Copy after login

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());
 })
}
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

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>
Copy after login
//.jsvar express=require("express");
var bodyParser=require(&#39;body-parser&#39;);
var app=express();
app.set(&#39;view engine&#39;,&#39;ejs&#39;)
app.get(&#39;/&#39;,function (req,res) {
 res.render("form");
});
//bodyParser API
app.use(bodyParser.urlencoded({extended:false}));
app.post(&#39;/&#39;,function (req,res) {
 console.log(req.body);
});
app.listen(3000);
Copy after login
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.js

How 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles