Express Middleware
Types
I list some middleware that frontend developer normally use to get data.There are several type of HTTP Request as following:
- query
- form
- path
- cookie
- header
Install and Declaration
npm install express
npm install cookie-parser
npm install body-parserconst express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
app.use(cookieParser())
// 请求体参数是: name=tom&pwd=123
app.use(express.urlencoded({extended: true}))
// 请求体参数是json结构: {name: tom, pwd: 123}
app.use(express.json())
//404 not find notice it is at the end
app.use((req,res,next)=>{
res.status(404).send('404')
})Read Data
GET
// query data
app.get('/',(req,res)=>{
res.json(req.query)
})
// path params
app.get('/abc:id',(req,res)=>{
res.json(req.params)
})POST
// form param => axios.post('/',{data:{'..':'..'}})
app.post('/',(req,res)=>{
res.json(req.body)
})BUT reading axios.post params using following
app.post('/',(req,res)=>{
res.json(req.query)
})Cookie
app.put('/',(req,res)=>{
res.json(req.cookies)
})Header
app.patch('/',(req,res)=>{
res.send(req.get('Content-Type'))
})