Let'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!
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 thenode operation.
If the response is:http://localhost:8080/login?goods1=0001&goods2=0002then Pass:
req.query
req.query.goods1 req.query.goods2
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>
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>
app.use(express.urlencoded())
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>登陆</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>
var express = require('express'); var path = require('path') var app = express(); var sqlQuery = require('./lcMysql') // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); //解析post提交的数据 app.use(express.urlencoded()) //搜索首页 app.get('/',(req,res)=>{ res.render('index.ejs') }) //登陆页 app.get('/login',(req,res)=>{ res.render('login') }) //处理登陆请求 app.post('/login',async (req,res)=>{ //获取用户名和密码 let username = req.body.username let password = req.body.password //查询数据库是否由此用户名和密码 let sqlStr = 'select * from user where username = ? and password = ?'; 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 request2.express accepts requestIntermediate processing process3.Routing function handles rendering (req, res) 4.res.render renderingThe 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.
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);
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);
const express=require("express"); var app=express(); app.use(function(req,res,next){ console.log("访问之前"); next(); },function(req,res){ res.send("主页"); }); app.listen(8080);
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('Not Found'); 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('express'); var app = express(); var cookieParser = require('cookie-parser');
以上就是关于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!

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

AI Hentai Generator
Generate AI Hentai for free.

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



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.

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.

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.

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

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.

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.

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

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.
