安装

脚手架 express-generator

npm install express-generator -g
express express-test
npm install & npm start

中间件

const express = require('express')

const app = express()

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

app.use((req, res, next) => {
  // 设置cookie
  req.cookie = {
    userid: '123'
  }
  next()
})

app.use((req, res, next) => {
  req.body = {
    username: 'susan',
    password: 123
  }
  next()
})

app.use('/api', (req, res, next) => {
  console.log('进入api')
  next()
})

app.get('/api', (req, res, next) => {
  console.log('进入get api')
  res.json({
    code: 0,
    data: req.cookie
  })
})

app.post('/api', (req, res, next) => {
  console.log('进入post api')
  res.json({
    code: 0,
    data: req.body
  })
})

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

app.listen(3000, ()=>{
  console.log('ok')
})

get请求/api                    post请求/api                404请求

请求开始... /api              请求开始... /api              请求开始... /api2
进入api        进入api                          处理 404
进入get api                    进入post api

中间件可以对接口进行权限验证

const check = (req, res, next) => {
  console.log('进入验证代码')
  // 验证成功
  // next()

  // 验证失败
  res.json({
    code: 1,
    msg: '验证失败'
  })
}

app.get('/api', check, (req, res, next) => {
  console.log('进入get api')
  res.json({
    code: 0,
    data: req.cookie
  })
})

 



 

posted on 2019-05-16 21:57  苏荷酒吧  阅读(154)  评论(0编辑  收藏  举报