express中间件的学习

 安装express 

npm i express --registry=https://registry.npm.taobao.org

中间件执行顺序:

  1. 首先响应app.use里面直接注册的函数
  2. app.use里面带有路由的 并且含有父路由的例如:/api这种的
  3. next函数是起到桥梁的作用,连接后面的函数。当该函数执行完会去执行后面能命中的函数。
  4. 没有next的方法为“最后需要执行的方法”。
const express = require('express');

// 本次 http 请求的实例
const app = express();

app.use((req, res, next) => {
    console.log('请求开始...', req.method, req.url)
    next()
});

app.use((req, res, next) => {
    // 假设在处理 cookie
    req.cookie = {
        userId: 'abc123'
    };
    next();
})

app.use((req, res, next) => {
    // 假设处理 post data
    // 异步
    setTimeout(() => {
        req.body = {
            a: 100,
            b: 200
        }
        next()
    })
})
//所有/api的路由都会响应
app.use('/api', (req, res, next) => {
    console.log('处理 /api 路由')
    next();
});
//所有get请求的都会响应
app.get('/api', (req, res, next) => {
    console.log('get /api 路由')
    next();
});
//所有post请求的都会响应
app.post('/api', (req, res, next) => {
    console.log('post /api 路由')
    next()
});

// 模拟登录验证
function loginCheck(req, res, next) {
    setTimeout(() => {
        console.log('模拟登陆失败')
        res.json({
            errno: -1,
            msg: '登录失败'
        })

        // console.log('模拟登陆成功')
        // next()
    })
}

app.get('/api/get-cookie', loginCheck, (req, res, next) => {
    console.log('get /api/get-cookie')
    res.json({
        errno: 0,
        data: req.cookie
    })
})

app.post('/api/get-post-data', loginCheck, (req, res, next) => {
    console.log('post /api/get-post-data')
    res.json({
        errno: 0,
        data: req.body
    })
})

app.use((req, res, next) => {
    console.log('处理 404')
    res.json({
        errno: -1,
        msg: '404 not fount'
    })
})

app.listen(3000, () => {
    console.log('server is running on port 3000')
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值