在Express中获取表单GET请求参数和POST请求体数据

在Express中获取表单GET请求参数

Express内置了一个API,可以直接通过req.query来获取

req.query

在Express中获取表单POST请求体数据

在Express中没有内置获取表单POST请求体的API,这里我们需要使用一个第三方包body-parser

安装:

npm install --save body-parser

配置:

var express = require('express')

//0.引包
var bodyParser = require('body-parser')

var app = express()
 
//配置 body-parser
//只要加入这个配置,则在 req 请求对象上会多出来一个属性 :body
//也就是说你就可以直接通过 req.body 来获取表单 POST 请求体数据了
// 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')
  //可以通过 req.body 获取表单数据
  res.end(JSON.stringify(req.body, null, 2))
})

猜你喜欢

转载自blog.csdn.net/cake_eat/article/details/109057522