在express中对get请求内置了req.query来获取请求数据,对post请求,需要配合使用body-parser中间件来获取
示例(来源于文档说明)
var express = require(‘express‘) var bodyParser = require(‘body-parser‘) var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.use(function (req, res) { res.setHeader(‘Content-Type‘, ‘text/plain‘) res.write(‘you posted:\n‘) res.end(JSON.stringify(req.body, null, 2)) })
现已弃用,可以直接调用express
// parse application/x-www-form-urlencoded app.use(express.urlencoded({ extended: false })) // parse application/json app.use(express.json()) app.use(router)
不需要安装和引入body-parser了,要记得一定在引入路由之前配置