Express JS - Handling POST request

时间:2018-03-25 20:37:19

标签: express

I am having trouble interpreting the following POST request sent via Postman in Express.js: (sending "temp": 97.7, "device": "one")

enter image description here

My POST router (in ./routes/sensors) is a simple

router.post('/', function(req, res, next) {
  console.log(req.body)
});

and my index.js contains

var sensorsRouter = require('./routes/sensors');

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use('/sensors', sensorsRouter);

Question: When I send the above mentioned POST request, my console understands it's a POST, but the output of req.body is empty: {}

How can I interpret the "temp" and "device" sent as a POST request in Express.js? I found many instructions involving body-parser, but as far as I understand express.json and express.urlencoded are supposed to be used instead these days.

1 个答案:

答案 0 :(得分:2)

我看到您的邮递员设置有误。即使您将请求类型设置为GET,您也会在URL中将数据作为POST数据发送。这是我的api的POST设置。

1.set标题content-typeapplication/json setting header

2.在正文选项卡中,从下拉框中选择raw选项和json/application。然后将您的数据作为json对象

Body