0

I have an API that works as expected from all incoming requests using application/json request. But recently I encounter the need to process a POST request from x-www-form-urlencoded and the body of the request is always empty.

I test the API using POSTMAN and works great when I send the request using the option raw with JSON(application/json). But when send data using x-www-form-urlencoded the body is empty.

The route for the POST is app/api/sensor, and the files are the following:

app.js

var express = require('express');
var app = express();

.......

app.use(express.json());
app.use(express.urlencoded());  // THIS SHOULD WORK!

......

sensor.js POST

......

sensorRoute.post('/', (req, res, next) => {

console.log(req.body);
const temperature = req.body.temperature;
console.log(temperature);

if (!temperature) {
    return res.status(400).send({'res': 'Missing data'});
} else {
    return res.status(200).send({'res': 'OK'});
}
});

....

The expected result should show the data that is been send using postman in the req.body and not an empty object, and work the same as the application/jason.

  • Possible duplicate of [req.body empty on posts](https://stackoverflow.com/questions/24543847/req-body-empty-on-posts) – user269867 Jun 02 '19 at 02:52

1 Answers1

1

change

app.use(express.urlencoded());  

to

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

The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.

Defaults to true, but using the default has been deprecated. so add the option extended: true

TRomesh
  • 4,323
  • 8
  • 44
  • 74
  • Did not work! But fixed using `sensorRoute.post('/', express.urlencoded(), (req, res, next) => {});`. Not ideal... but worked. – user9196017 Jun 05 '19 at 16:41