javascript - Express body-parser : req. body 返回空对象

标签 javascript node.js express body-parser

我有一个简单的 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/

相关文章:

javascript - 如何在不打开 native 应用程序的情况下使用 PhoneGap 发送短信?

javascript - 使用 GET 请求获取详细信息时,返回 401 错误

node.js - 在 Typescript 中扩展 Express 中间件

node.js - 如何从作为库运行的 postgraphile 获取查询结果

node.js - 运行-p : command not found

javascript - clearInterval 对我不起作用

javascript - 更改折叠的导航栏列表背景颜色

javascript - 使用nodejs上传大文件

javascript - 如何使用 Nodemailer 附件的相对路径?

javascript - 无法获取/api/任务