路由模块化以及Express中间件的使用

路由模块化

将app上直接绑定的get/post等请求封装到一个js中

const express = require("express")
const Router = express.Router()


Router.get("/user", (req , res)=>{
    res.send({"name":"梦想","age":"20","gender":"男"})
})

Router.post("/user" , (req , res)=>{
    res.send("不要过来啊")
})

Router.get("/" , (req , res)=>{
    res.send(req.query)
})
Router.get("/user/:id" , (req , res)=>{
    res.send(req.params)
})

module.exports = Router


//router.js

在创建服务器的文件中使用


const router = require("./router")

const app = express();

app.use(router)

//或app.use("/api" , router)  可以为所有router中请求绑定一个固定前缀url  /api

Express中间件有五类

1.直接绑定在app实例上的

2.绑定在router实例上的

3.错误处理的

4.express自带的

5.第三方定义的

全局使用(除了错误处理以外的中间件都需放在挂在post/get等请求之前)

中间件使用方式

const mw = function(req , res , next){
    console.log("这是一个中间件");
    next(); //调用该函数放行到下一个中间件
}

app.use(mw)



//普通的一个中间件

多个中间件执行顺序

const mw = function(req , res , next){
    console.log("这是一个中间件1");
    next();
}

const mw1 = function(req , res , next){
    console.log("这是一个中间件2");
    next();
}

app.use(mw)

app.use(mw1)

//输出
//    这是一个中间件1
//    这是一个中间件2  

中间件调用顺序按照use顺序依次调用

错误处理中间件

const mw = function(err ,req , res , next){
    console.log("发生错误"+err.message) 
}

//错误处理中间件必须放在挂载路由之后.
//错误处理中间件会在前面中间件或路由抛出错误后执行.

express自带的中间件

app.use(express.static("")) 
app.use(express.json())  //解析请求体json格式数据  解析后挂载在req.body属性上
app.use(express.urlencoded({extended:false}))  //解析请求体URL-encoded格式数据 解析后挂载在    
                                               //req.body属性上

局部中间件使用

const mw = function(req , res , next){
    console.log("这是一个中间件1");
    next();
}

Router.get("/user",mw, (req , res)=>{
    res.send({"name":"梦想","age":"20","gender":"男"})
})

//直接写在单个路由请求的回调函数中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值