Express中解析post请求数据-- 中间件(bodyParser)

    技术2025-05-26  27

    解析post请求数据

    http://expressjs.com/en/starter/static-files.html 官网上

    使用插件的原因:

    req.query 注意: query只能拿到get 通过url传递的数据。 post 不是通过路径传参,

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

    Installation 安装

    $ cnpm install body-parser

    API

    var bodyParser = require('body-parser')

    官方案例:

    var express = require('express') var bodyParser = require('body-parser')// 1.先引入包 var app = express() //配置body-parser //只要加入这个配置,则在req请求对象上,会多出来一个属性:body //也就是说你可以直接通过 req.body 来获取变淡post请求体数据了、 // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) //2. use往app上添加方法 // parse application/json app.use(bodyParser.json()) //2. use往app上添加方法 app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('you posted:\n') res.end(JSON.stringify(req.body, null, 2)) //3. req.body 获取数据 })

    补充: 浏览器输入地址 敲回车,永远是get请求。 post请求方式 :1. table表格提交, 2.Ajax请求发起

    本地测试代码:

    // 0 安装 // 1 引包 const express = require('express') // 引包 var bodyParser = require('body-parser')// 先引入包 const app = express() //调用 app.engine('html', require('express-art-template')); var comments = [{ name: '张四', message: '今天是个好日子', dataTime: '2020.03.03' }, { name: '张三', message: '今天是个好日子', dataTime: '2020.03.03' } ] app.get('/', function(req, res){ res.render('index.html',{ //1. 使用render方法 comments:comments }) }) app.get('/post', function(req, res){ res.render('post.html') }) app.get('/pinglun', function(req, res){ console.log('进来了'); var comment = req.query comment.dataTime = '2020-11-02' comment.message = (comment.message).trim() comments.unshift(comment) res.redirect('/') }) app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) app.post('/post',function(req,res){ // req.query 注意: query只能拿到get 通过url传递的数据。 get 不是通过路径传参 var comment = req.body // 加载这个插件,就为了这一句 < -------- comment.dataTime = '2020-11-02' comment.message = (comment.message).trim() 本案例在这里: 注意这个插件只是帮助拿到数据, 其 他保持不变 comments.unshift(comment) res.redirect('/') }) app.use('/public/', express.static('./public/')) app.use('/node_modules/', express.static('./node_modules/')) app.listen(3000, function(){ console.log('running...') })
    Processed: 0.010, SQL: 9