Home >Web Front-end >JS Tutorial >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.
##Related recommendations: "nodejs Tutorial"
Before that, let me talk about a very useful one——nodemon——> ; After automatic compilationnpm install nodemon -D, modify the "start" field in the "script" option in the configuration file json as follows:
"start":"nodemon js路径+名", //增加一行 "start:node":"node js路径+名", ...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"] }(src is at the same level as json (where js is located) Directory name)After this, the server can automatically
npm start.
npm install express -S # "-S":在生产环境中搭载 npm install nodemon -DSet 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('启动成功'); });
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", ...How to pass parameters in the above code?
// get方式传参 app.get('/name/:age',(req,res)=>{ let {age}=req.params; res.json({ name:'tom', age }) })
web service url --> Network --> dns Analysis --> How does the target server
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 }) });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 }) });
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;In app.js "
Register route":
const memberRouter=require('./member.router.js');app.use(memberRouter);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?
const memberRouter=require('./member.router.js'); app.use(memberRouter);
express middleware
Usage: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); });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?
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(); }); }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); });
Exception handling
General approach:
throw new Error('Test function exception');
node-express built-in exception handling: <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>
ORM in actual combat Model creation
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!