说明
本文介绍 POST 请求中,获取请求体数据
引入 body-parser 模块:
const bodyParser = require('body-parser');
使用 body-parser 中间件解析请求体:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
获取请求体数据:
const { name, age } = req.body;
完整代码
// 引入 express 模块
const express = require('express');
const bodyParser = require('body-parser');
// 创建 express 对象
const app = express();
// 指定监听端口
const port = 8081;
// 使用body-parser中间件解析请求体
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/login', (req, res) => {
const { username, password } = req.body;
console.log(username, password )
// 发送内容
const data = {
code: 0,
msg: '登录成功!'
};
res.json(data);
})
// 启动服务,监听端口
const server = app.listen(port, function () {
// var host = server.address().address
// var port = server.address().port
console.log("服务启动成功,监听端口是", port)
})
前端代码
fetch请求:
// 发送 POST 请求,携带请求体数据
fetch('http://localhost:8081/login', {
method: 'POST', // 指定请求方法
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ // 携带数据
username: 'lilei',
password:'123456'
})
})
.then(response => response.json())
.then( data => {
console.log("data:",data)
}).catch(err => {
console.log("err:",err)
})