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

Detailed explanation of express in nodejs

青灯夜游
Release: 2021-03-11 10:09:25
forward
2731 people have browsed it

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!

Related labels:
source:csdn.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!