node express包获取参数的方法

160 阅读1分钟

get请求

通过 res.query 获取查询字符串

// 请求路径:127.0.0.1/test?name=lihua&age=18

app.get('/test',(req,res)=>{
    console.log(req.query)  //{ name: 'lihua', age: '18' }
})

post请求

1.通过 内置中间件 访问请求参数格式为 x-www-form-urlencodedjson 的参数

/*
    无论请求的参数为urlencoded或者json都能被node的内置中间件解析
*/
app.use(express.urlencoded({extended:false})) // 解析urlencode格式的中间件
app.use(express.json()) // 解析json格式的中间件

app.post('/test',(req,res) =>{
    console.dir(req.body); //通过req.body获取参数转化成的对象 { id: '3', name: 'lihua\n', group: '第三组' }
    res.send(req.body)   
})

例子:

image.png

image.png

2.通过自定义中间件来解析
可以去查看 querystring 包的用法

const qs = require('querystring')

app.use((req,res,next)=>{
    let str = '';
    // 监听data事件
    req.on('data',(chunk)=>{
        str += chunk;
    })
    //鉴定end事件
    req.on('end',()=>{
        // 2.把字符串格式的请求体数据解析成对象格式,使用querystring模块解析请求体数据
        let body = qs.parse(str)
        req.body = body

        next() // next() 在这里确保会执行上面的步骤
    })
    // 这里不能写next(),因为req.on里的回调函数会放到事件循环里面,并不会立即执行,next()在这里的话会先执行,这样req.on里面的回调就不会执行到
    // next() 错误!!!
})

app.post('/test',(req,res) =>{  
    // 将对象解析为 
    res.send(JSON.stringify(req.body))
})