


Detailed explanation of the use of node.js routing middleware ge and post requests
This time I will bring you a detailed explanation of the use of node.js routing middleware ge and post requests. What are the precautions for using node.js routing middleware ge and post requests. The following is a practical case. , let’s take a look.
1. Routing
1. What is routing
The server needs to perform different operations according to different URLs or requests. We can achieve 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 access to a website address
app.post("网址",function(req,res){ });
2.3. Any request to visit this website
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. Use of regular expressions in routing
3.1. In regular expressions, the unknown parts are grouped with parentheses, and can 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 (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);
2. Middleware
1. What is middleware
Applied to serve as a connection service between applications, 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 and login can be used 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)
Operational results: When we access 172.0.0.1:3000/admin/login, only the user information admin will be output instead of the administrator login
2.3. Resolve sequence conflicts
2.3.1. Write the concrete ones at the top and the abstract ones at the bottom.
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, Retrieve dataLibrary
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()Read file
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, res.send() method quick test page
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);
operation result:
3. getRequest parameterspost 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, then you still need to use the formidable module.
//form.ejs nbsp;html> <meta> <title></title>
//.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);
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Bootstrap modal box pops up multiple times to submit a BUG
vue-cli How to configure lib-flexible rem mobile terminal Adaptive
The above is the detailed content of Detailed explanation of the use of node.js routing middleware ge and post requests. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

PHP is a programming language widely used in website development, and page jumps and carrying POST data are common requirements in website development. This article will introduce how to implement PHP page jump and carry POST data, including specific code examples. In PHP, page jumps are generally implemented through the header function. If you need to carry POST data during the jump process, you can do it through the following steps: First, create a page containing a form, where the user fills in the information and clicks the submit button. Acti in the form

Title: PHP code example: How to use POST to pass parameters and implement page jumps In web development, it often involves the need to pass parameters through POST and process them on the server side to implement page jumps. PHP, as a popular server-side scripting language, provides a wealth of functions and syntax to achieve this purpose. The following will introduce how to use PHP to implement this function through a practical example. First, we need to prepare two pages, one to receive POST requests and process parameters
