Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the use of node.js routing middleware ge and post requests

php中世界最好的语言
Release: 2018-04-13 14:38:48
Original
1595 people have browsed it

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

      2.2. What to do when post requests access to a website address          

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

    2.3. Any request to visit this website  

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

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

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

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

  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);
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

operation result:

Detailed explanation of the use of node.js routing middleware ge and post requests

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>


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

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template