search
HomeWeb Front-endJS TutorialLet's talk about get/post requests and middleware in nodejs

This article will take you through hot restart, get request, post request and middleware in node.js. I hope it will be helpful to everyone!

Let's talk about get/post requests and middleware in nodejs

1. Hot restart of node

1. Installation

npm i nodemon

2. Run and start

nodemon .bin/www

## 2. About get request

Generally in website development, get is used for data acquisition and query, similar to the query operation in the database. When the server parses the foreground resource, it transmits the corresponding content; and the query string It is performed on the URL, in the form:

http://localhost:8080/login?goods1=0001&goods2=0002

Get the front-end get request

The get request sent by the user can be obtained through req.query, and then the corresponding data is returned to the user through the

node operation.

If the response is:

http://localhost:8080/login?goods1=0001&goods2=0002


then Pass:

req.query

He will get all the data, or

req.query.goods1
req.query.goods2

to separate or remove each data. In short, different needs correspond to different businesses, and everyone can obtain it according to their own needs;

Example

The following is an example of how to get get A summary of the parameters:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form action="http://localhost:8080/login" method="get">
            用户:
            <input type="text" name="user" id="user" placeholder="用户名"/>
            <br>
            密码:
            <input type="password" name="password" id="password" placeholder="密码"/>
            <br>
            <input type="submit" value="提交"/>
        </form>
    </body>
</html>

node:

const express = require("express");
var app = express();

app.get("/",function(req,res){
    res.send("主页");
});

app.get("/login",function(req,res){
    console.log(req.query);
    res.send("登录路由,user为:"+req.query.user+"==>   password为:"+req.query.password);
});

app.listen(8080);

3. About POST request

post method as http The request is an important part and is used by almost all websites. Unlike the get request, the post request is more like a modification operation on the server. It is generally used for updating data resources. Compared with get requests, the data requested by post will be more secure. In the previous chapter, we found that the get request will display the entered user name and password in the address bar (converted to BASE64 encryption when there is Chinese), while the post request will put the data into the body of the http package, which makes it impossible for others to directly See username and password!

How does Express set up a POST request?

1. First we need to know how to make a post request in the form,

enctype attribute Generally set to "application/x-www-form-urlencoded", if set to multipart/form-data, it is mostly used for file upload, as follows:

<form action="#" method="post" enctype="application/x-www-form-urlencoded">
</form>

2. Set up parsing body middleware

app.use(express.urlencoded())

3. Get body data

req.body.username

Login case:

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1 id="登陆">登陆</h1>
    <form action="/login" method="POST">
        <div>
            用户名:<input type="text" name="username">
        </div>
        <div>
            密码:<input type="password" name="password">
        </div>
        <button>登陆</button>
    </form>
      
</body>
</html>

APP.JS

var express = require(&#39;express&#39;);
var path = require(&#39;path&#39;)
var app = express();
var sqlQuery = require(&#39;./lcMysql&#39;)

// view engine setup
app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));
app.set(&#39;view engine&#39;, &#39;ejs&#39;);
app.use(express.static(path.join(__dirname, &#39;public&#39;)));
//解析post提交的数据
app.use(express.urlencoded())

//搜索首页
app.get(&#39;/&#39;,(req,res)=>{
  res.render(&#39;index.ejs&#39;)
})

//登陆页
app.get(&#39;/login&#39;,(req,res)=>{
  res.render(&#39;login&#39;)
})
//处理登陆请求
app.post(&#39;/login&#39;,async (req,res)=>{
  //获取用户名和密码
  let username = req.body.username 
  let password = req.body.password
  //查询数据库是否由此用户名和密码
  let sqlStr = &#39;select * from user where username = ? and password = ?&#39;;
  let arr = [username,password];
  let result = await sqlQuery(sqlStr,arr)
  if(result.length == 0 ){
    res.send("登陆失败")
  }else{
    res.send("登陆成功")
  }

})


module.exports = app;

4. Middleware

From the literal meaning, we can understand that it is probably an intermediate proxy operation, and this is also the case; in most cases Below, the middleware is performing a series of operations between receiving the request and sending the response. In fact, express is a web framework for routing and middleware, and an Express application is basically a series of middleware function calls.

1. Browser sends request

2.express accepts request

Intermediate processing process

3.Routing function handles rendering (req, res)

4.res.render rendering

The middleware function can perform the following tasks:

    Execute any code.
  • Make changes to request and response objects.
  • End the request/response cycle.
  • Call the next middleware function in the stack.
Middleware is also divided into application layer middleware, routing middleware, built-in middleware, error handling middleware and third-party middleware. The following are explained respectively:

1. Application layer middleware

The application-level middle key is bound to the app object using app.use And app.METHOD() - methods that need to handle http requests, such as GET, PUT, POST, just replace the previous get or post with use. For example, the following example:

const express=require("express");

var app=express();

//匹配路由之前的操作
app.use(function(req,res,next()){
    console.log("访问之前");
});

app.get("/",function(req,res){
    res.send("主页");
});

app.listen(8080);

At this time we will find that the

http://localhost:8080/ address has been loading, but the command line displays "before access", indicating that the program does not It will be executed synchronously. If you use next to continue matching the route downwards, you can get the homepage data again:

const express=require("express");

var app=express();

//匹配路由之前的操作
app.use(function(req,res,next){
    console.log("访问之前");
    next();
});

app.get("/",function(req,res){
    res.send("主页");
});

app.listen(8080);

Of course, you can also simplify the writing:

const express=require("express");

var app=express();

app.use(function(req,res,next){
    console.log("访问之前");
    next();
},function(req,res){
    res.send("主页");
});

app.listen(8080);

Therefore, when performing route matching If you want to perform an operation before or after recording and continue to execute, application layer middleware is undoubtedly a good choice.

2.路由中间件

路由级中间件和应用级中间件类似,只不过他需要绑定express.Router();

var router = express.Router()

在匹配路由时,我们使用 router.use() 或 router.VERB() ,路由中间件结合多次callback可用于用户登录及用户状态检测。

const express = require("express");
var app = express();
var router=express.Router();

router.use("/",function(req,res,next){
    console.log("匹配前");
    next();
});

router.use("/user",function(req,res,next){
    console.log("匹配地址:",req.originalUrl);
    next();
},function(req,res){
    res.send("用户登录");
});

app.use("/",router);

app.listen(8080);

总之在检测用户登录和引导用户应该访问哪个页面是,路由中间件绝对好用。

3.错误处理中间件

顾名思义,它是指当我们匹配不到路由时所执行的操作。错误处理中间件和其他中间件基本一样,只不过其需要开发者提供4个自变量参数。

app.use((err, req, res, next) => {
        res.sendStatus(err.httpStatusCode).json(err);
});

一般情况下,我们把错误处理放在最下面,这样我们即可对错误进行集中处理。

const express=require("express");

var app=express();

app.get("/",function(req,res,next){
    const err=new Error(&#39;Not Found&#39;);
    res.send("主页");
    next(err);
});

app.use("/user",function(err,req,res,next){
    console.log("用户登录");
    next(err);
},function(req,res,next){
    res.send("用户登录");
    next();
});

app.use(function(req,res){
    res.status(404).send("未找到指定页面");
});

app.listen(8080);

4.内置中间件

从版本4.x开始,Express不再依赖Content,也就是说Express以前的内置中间件作为单独模块,express.static是Express的唯一内置中间件。

express.static(root, [options]);

通过express.static我们可以指定要加载的静态资源。

5.第三方中间件

形如之前我们的body-parser,采用引入外部模块的方式来获得更多的应用操作。如后期的cookie和session。

var express = require(&#39;express&#39;);
var app = express();
var cookieParser = require(&#39;cookie-parser&#39;);

以上就是关于express中间件类型,在实际项目中,中间件都是必不可少的,因此熟悉使用各种中间件会加快项目的开发效率。

更多node相关知识,请访问:nodejs 教程!!

The above is the detailed content of Let's talk about get/post requests and middleware in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use