需要下载node

1,。新建文件-serve,打开终端

2,.下载express,body-parser

npm init -y

npm install express body-parser --save

新建userApi.json

{
"code": 0,
"result": [
    {
    "uid": 1,
    "name": "name",
    "email": "email"
    }
]
}

 

3.新建index.js

var express = require('express')
var bodyParser = require('body-parser')
var userApi = require('./api/userApi.json')
console.log(userApi)
const localPort = 8888
var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

app.post('/api/user', (req, res) => {
    console.log('********************')
    console.log(req.body)
    res.send(userApi)
    res.end();
})

app.listen(localPort, () => {
    console.log('***********************', localPort)
})


 

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

  

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

注:如果在模拟器上以非JSON格式发送,则会获得一个空的JSON对象,不使用中间件,直接获取body为undefined

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

urlencodedParser

2、加载到没有挂载路径的中间件

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

 

posted on 2022-06-14 17:10  千寻岛主  阅读(378)  评论(0编辑  收藏  举报