express

安裝express

腳手架 express-generatornpm

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

中間件json

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              請求開始... /api              請求開始... /api2
進入api        進入api                          處理 404
進入get api                    進入post apicookie

中間件能夠對接口進行權限驗證app

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
  })
})
相關文章
相關標籤/搜索