Home Web Front-end JS Tutorial Detailed explanation of express in nodejs

Detailed explanation of express in nodejs

Mar 11, 2021 am 10:09 AM
express 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.

Detailed explanation of express in nodejs

##Related recommendations: "

nodejs Tutorial"

Before that, let me talk about a very useful one——nodemon——> ; After automatic compilation

npm install nodemon -D
Copy after login
, modify the "start" field in the "script" option in the configuration file json as follows:

"start":"nodemon js路径+名",
//增加一行
"start:node":"node js路径+名",
...
Copy after login
But now we find a problem: no matter what file is used, Any changes will restart the node.

We simply specify: monitor js files:

Create new nodemon.json

{
	"watch":["./src/**/*.js"]
}
Copy after login
(src is at the same level as json (where js is located) Directory name)

After this, the server can automatically

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 application

npm install express -S       # "-S":在生产环境中搭载
npm install nodemon -D
Copy after login
Set app.js under the src directory (self-built folder):

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('启动成功');
});
Copy after login
See the code Line 3, have you thought of http?


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!

Modify in package.json (generated configuration file):

// "script"选项下第一个——"start"值中加一个“nodemon”字样:
"start":"nodemon ./src/app.js",
...
Copy after login
How to pass parameters in the above code?

// get方式传参
app.get('/name/:age',(req,res)=>{
	let {age}=req.params;
	res.json({
		name:'tom',
		age
	})
})
Copy after login

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已启动');
});
Copy after login

Routing API

Define an api that needs to satisfy the client that it can get a response no matter what request it makes

app.all('/demo',(req,res)=>{
	res.json({
		message:'demo',
		method:req.method
	})
});
Copy after login
No matter what URI the client uses, our service can respond (log)

app.all('*',(req,res)=>{
	res.json({
		message:'demo',
		method:req.method,
		uri:req.path
	})
});
Copy after login

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

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;
Copy after login
In app.js "

Register route":

const memberRouter=require('./member.router.js');app.use(memberRouter);
Copy after login
Now we write another route for skuRouter, which also has "/list" in its URI.

After registration. We find that we can't find it (can't print it out), what should we do?

In fact, we can add a "prefix" - that is, the "root" - to the routing use to distinguish it:

const memberRouter=require('./member.router.js');
app.use(memberRouter);
Copy after login

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>
Copy after login
npm install body-parser
Copy after login
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);
});
Copy after login
There is no doubt that this is an "extra" line than usual:

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?

Obviously not. The body doesn’t exist in the first place! (Otherwise, ajax still uses data?)


But we really need it now. So in line 2
const bodyParser=require('body-parser');

applies for the "middleware module", and in line 5 the entire "chain operation" (two uses connected) is given to "install Got on a body.

Generally speaking, in actual combat, we will write three middlewares to form a "complete" parameter parsing method:

app.use(express.json()) ;


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

req.query
directly in the node. There is no need for middleware.

So since middleware is so "useful", why not encapsulate one yourself?

mxc-body-parser.js file


// 仿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();
	});
}
Copy after login
Then reference it in other files:
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);
});
Copy after login

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

连接成功后会生成config.json配置文件,我们在development选项中修改和添加:

"database":"数据库表名",
"timezone":"+08:00"
Copy after login

持久化模型对应的数据库表:

npx sequelize db:migrate
Copy after login

前端数据如何往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;
};
Copy after login

使用:创建第一个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)
	}
})
Copy after login

最后的next传给谁?

我们之前说,在全局最后创建一个use,用于错误处理:

app.use((err,req,res,next)=>{
	if(err){
		res.status(500).json({
			message:err.message
		})
	}
})
Copy after login

更多编程相关知识,请访问:编程入门!!

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!

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

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.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

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.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

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

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

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.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

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.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

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.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

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

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

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.

See all articles