express框架中读取post请求发送来的数据是空对象为什么该怎么解决
可能是因为没有使用中间件来解析post请求的数据。可以使用body-parser中间件来解析post请求的数据。
-
首先安装body-parser:npm install body-parser --save
-
在Express应用中引入body-parser中间件:
const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true }));这里使用了urlencoded解析器来解析post请求的数据。
-
在post请求处理函数中,可以通过req.body来获取post请求发送来的数据,例如:
app.post('/login', function(req, res) { let username = req.body.username; let password = req.body.password; console.log('username:', username); console.log('password:', password); res.send('login success'); });
原文地址: https://www.cveoy.top/t/topic/bd2R 著作权归作者所有。请勿转载和采集!