shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 510 forks source link

【Q633】Node 中服务端框架如何解析 http 的请求体 body #651

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

在 Node 服务中,通过 http.createServer 接收到的 req 为可读流,对流进行读取数据

const server = http.createServer((req, res) => {
  let body = ''
  req.on('data', chunk => body += chunk)
  req.on('end', () => {
    data = body
    res.end(data)
  })
})
Asarua commented 3 years ago

body-parser?