zoukankan      html  css  js  c++  java
  • express获取post传参数据:body-parser使用详解

    一、简介

    二、使用

      搭建一个简单的demo

    mkdir body-parser-demo
    cd body-parser-demo
    
    npm init -y
    npm install express body-parser --save

      新建index.js

    var express = require('express')
    var bodyParser = require('body-parser')
    
    const localPort = 3000
    var app = express()
    
    // create application/json parser
    var jsonParser = bodyParser.json()
    
    // create application/x-www-form-urlencoded parser
    var urlencodedParser = bodyParser.urlencoded({ extended: false })
    
    
    app.post('/login.do', (req, res) => {
        console.log('********************')
        console.log(req.body)
    
        res.end();
    })
    
    app.listen(localPort, () => {
        console.log('http://127.0.0.1:%s', host, port)
    })

      执行node index.js,网络模拟请求使用Postman工具

      不使用中间件,直接获取body为undefined

    1、JSON解析器

    app.post('/login.do', jsonParser, (req, res) => {
        console.log('********************')
        console.log(req.body)
        res.end();
    })

      注:如果在模拟器上以非JSON格式发送,则会获得一个空的JSON对象

      urlencoded解析器即将上述代码的 jsonParser 换成 urlencodedParser 即可

    2、加载到没有挂载路径的中间件
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    // parse application/json
    app.use(bodyParser.json())
     
  • 相关阅读:
    python 学习
    快速排序
    U3D AStar 案例
    U3D AStar 算法原理
    .net core 实时通讯
    .net 算法复杂度
    U3D MVC 背包案例
    U3D 对象池
    Unity网络基础(NetWork)
    U3D Socket实现简易通讯
  • 原文地址:https://www.cnblogs.com/goloving/p/12482994.html
Copyright © 2011-2022 走看看