Express中获取get和post请求的数据

获取 get 请求的数据

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

// 在express中可以直接通过 request.query 来获取字符串参数
// http://127.0.0.1:4000/about?name=zhangsan&message=hello
app.get('/about',function (request,response) {
    
    
  console.log(request.query);
  response.send('关于我');
})

返回的数据格式:{ name: 'zhangsan', message: 'hello' }


获取 post 请求的数据

在Express中没有内置获取 post 请求体的API,我们需要使用第三方插件 body-parser

安装 npm install body-parser

配置 body-parser

  • 进行下方代码的配置,就会在 request 请求对象上就会多出来一个属性:body
  • 我们就可以直接通过 request.body 来获取表单 POST 请求体的数据了
app.use(bodyParser.urlencoded({
    
     extended: false }))
app.use(bodyParser.json())

使用

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

app.use(bodyParser.urlencoded({
    
     extended: false }))
app.use(bodyParser.json())

app.post('/about',function (request,response) {
    
    
  console.log(request.body);
})

参考资料

Express中间件 body-parser

延伸阅读 https://blog.csdn.net/weixin_43974265/category_10692693.html

猜你喜欢

转载自blog.csdn.net/weixin_43974265/article/details/112063577