Detailed explanation of express in nodejs
This article will introduce to you express in node. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
nodejs Tutorial"
Before that, let me talk about a very useful one——nodemon——> ; After automatic compilationnpm install nodemon -D
"start":"nodemon js路径+名", //增加一行 "start:node":"node js路径+名", ...
Create new nodemon.json
{ "watch":["./src/**/*.js"] }
npm start.
Getting back to the topic, Express takes action
Our first understanding of express: a web framework in node. As follows: Use express to build a web applicationnpm install express -S # "-S":在生产环境中搭载 npm install nodemon -D
const express=require('express'); //一个express实例 const app=express(); //app.use((req,res)=>{ // res.json({ // name:"张上" // }) //}) app.get('/name',(req,res)=>{ let {age}=req.params; res.send('tom'); }); app.post('/name',(req,res)=>{ res.send('tom post'); }); app.listen(8081,()=>{ console.log('启动成功'); });
See the code Line 3, have you thought of http?Modify in package.json (generated configuration file):
const server=http.createServer((req,res)=>{...});The server here is the same as the app above. But the two reqs are different, because the app's req is encapsulated by express, and it has richer functions!
// "script"选项下第一个——"start"值中加一个“nodemon”字样: "start":"nodemon ./src/app.js", ...
// get方式传参 app.get('/name/:age',(req,res)=>{ let {age}=req.params; res.json({ name:'tom', age }) })
Introduction to Router & How to process a request using
web service url --> Network --> dns Analysis --> How does the target server
- respond to this request——Routing! (Rules)
- How to distinguish——Request method (get/post), uri (path)
const express=require('express'); const app=express(); //1.请求方法判断 ——测试工具:postman app.get('/demo',(req,res)=>{ res.json({ message:'hello get mxc' }) }); app.post('/demo',(req,res)=>{ res.json({ message:'hello post mxc' }) }); //2.通过URI ——postman上测试:http://127.0.0.1:8081/user/byname?name=mxc //或:http://127.0.0.1:8081/user/byid?id=123 app.get('/user/byname',(req,res)=>{ let {name}=req.query; res.json({ name }) }); app.get('/user/byid',(req,res)=>{ let {id}=req.query; res.json({ id }) }); app.listen(8081,()=>{ console.log('server已启动'); });
Routing API
Define an api that needs to satisfy the client that it can get a response no matter what request it makesapp.all('/demo',(req,res)=>{ res.json({ message:'demo', method:req.method }) });
app.all('*',(req,res)=>{ res.json({ message:'demo', method:req.method, uri:req.path }) });
app.use --> Middleware
app.use('/demo',(req,res)=>{ res.json({ message:'from use demo', method:req.method }) }); app.use((req,res)=>{ res.json({ message:'demo', method:req.method, uri:req.path }) });
How to split routing? —— express.Router
In the member.router.js file:const express=require('express'); const router=express.Router(); //router.[method]//(get/post) //router.all //router.use router.get('/list',(req,res)=>{ res.json({ list:[ id:001, name:'mxc' ] }) }); module.exports=router;
Register route":
const memberRouter=require('./member.router.js');app.use(memberRouter);
After registration. We find that we can't find it (can't print it out), what should we do?
const memberRouter=require('./member.router.js'); app.use(memberRouter);
Middleware
express middleware
Usage:- app level usage (when registering, it must be at the top level/end)
- router level ##Exception handling
- ##(Normal) middleware
We should first consider a question: why "middleware" is needed: the program cannot be "completed" in one step.
For example, take the following demo: Get the input content:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <form action="http://localhost:8081" method="post"> 用户:<input type="text" name="user" /><br /> 密码:<input type="password" name="pass" /><br /> <input type="submit" value="提交"> </form> </body> </html>
npm install body-parser
const express=require('express'); const bodyParser=require('body-parser'); var server=express(); server.listen(8081); server.use(bodyParser,urlencoded({})); // 上面一行有时也写为:server.use(bodyParser,urlencoded({extended:true})); server.use('/',function(req,res){ console.log(req.body); });
server.use(bodyParser,urlencoded({ }));
is the so-called "use of middleware".Now it’s time to think about another question: Why does the program “can’t be completed in one step”?
As shown in the above code, should there be "body" in the req of POST?
But we really need it now. So in line 2
const bodyParser=require('body-parser');
Generally speaking, in actual combat, we will write three middlewares to form a "complete" parameter parsing method:
app.use(express.json()) ;directly in the node. There is no need for middleware.req.query
app.use(express.urlencoded());
app.use(bodyParser,urlencoded({extended:true}));
//Then get/post operation
Of course, if the previous submission is in GET mode, just use
So since middleware is so "useful", why not encapsulate one yourself?
// 仿body-parser中间件 const querystring=require('querystring'); module.exports=function(req,res,next){ var str=''; req.on('data',function(data){ str+=data; }); req.on('end',function(){ req.body=querystring.parser(str); next(); }); }
const express=require('express'); const mxcParser=require('./lib/mxc-body-parser'); var server=express(); server.listen(8081); server.use(mxcParser); server.use('/',function(req,res){ console.log(req.body); });
Exception handling
——Visualization Usually, exception handling is performed globally.
General approach:
throw new Error('Test function exception');
node-express built-in exception handling: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">function error_handler_middleware(err,req,res,next){
if(err){
let {message}=err;
res.status(500).json({
message:`${message || '服务器异常'}`
})
}else{
//其余操作
}
}
...
app.use(error_handler_middleware); //放在所有Router最后,做中间件用</pre><div class="contentsignin">Copy after login</div></div>
ORM in actual combat Model creation
Let’s talk about database initialization first
After creating mysql, we need to connect node to mysql. The tools used:
npm install express mysql2 sequelize nodemon sequelize-cli -S
连接成功后会生成config.json配置文件,我们在development选项中修改和添加:
"database":"数据库表名", "timezone":"+08:00"
持久化模型对应的数据库表:
npx sequelize db:migrate
前端数据如何往mysql中写?
调用todo.js模块:
use strict' ; module. exports = (sequelize, DataTypes) => { const Todo = sequelize.define( 'Todo', { name: DataTypes. STRING, deadLine: DataTypes .DATE, content: DataTypes. STRING },{ timestamps:false }) ; Todo. associate = function(models) { // associations can be def ined here }; return Todo; };
使用:创建第一个todo:(初始时)
app.post('/create',async (req,res,next)=>{ try{ let {name,deadline,content}=req.body; //持久化到数据库 let todo=await models.Todo.create({ name, deadline, content }) res.json({ todo, message:'任务创建成功' }) }catch(err){ next(error) } })
最后的next传给谁?
我们之前说,在全局最后创建一个use,用于错误处理:
app.use((err,req,res,next)=>{ if(err){ res.status(500).json({ message:err.message }) } })
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Detailed explanation of express 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.

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

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 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.
