我有一个简单的 Express 服务器,它使用 body-parser
模块来访问 POST 参数。该应用程序如下所示:
/index.js:
'use strict';
const express = require('express');
const app = express();
const apiRouter = require('./api/routes.js');
// Set our port for the server application
const port = process.env.PORT || 8080;
// Register the routes for the /api prefix
app.use('/api', apiRouter);
// Start server
app.listen(port);
console.log('The server is running on port ' + port);
/api/routes.js:
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Configure app to use bodyParser(). This will let us get the data from a POST
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
// START ROUTES
router.post('/devices', (req, res) => {
console.log(req.body); // Returns {}
res.json(req.body);
});
module.exports = router;
问题在于 req.body
对象为空(Always 返回空对象 {}
)。由于我已经加载了 body-parser
中间件,我不知道还能尝试什么。希望大家有什么建议。
最佳答案
我使用Postman应用程序进行测试。它似乎将 POST 数据作为 form-data
发送,而不是 x-www-form-urlencoded
。更改此设置后,数据就会显示出来。
关于javascript - Express body-parser : req. body 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46981778/