Marta
Marta

Reputation: 25

Empty body in POST requests to an API in NodeJS from Postman (but not from automated tests)

In POST requests through Postman in a NodeJS API I receive empty bodies... (I receive exactly this: {}), however from automated tests it works perfectly. Actually from Postman that happends when I send it as "form" or as "raw" with "text", but if I send it as a "JSON" in raw it simply freezes in "loading..."
When I search I read about adding these 2 lines related to body parse it made it work for the tests but not for Postman:

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

The entire code is here: https://github.com/nemenosfe/TakeMe-Api But the 3 key files are the following (simplified):

app.js:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const cors = require('cors');
const user = require('./routes/users');

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

app.use('/users', user);

app.use(cors());

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
});

app.listen(8888, function() {
  console.log("Node server running on http://localhost:8888");
});

module.exports = app;

routes/users:

"use strict"
const express = require('express'),
      router = express.Router(),
      /* ... many require and other code probably not relevant for the problem ... */

router
  .post('/', function(req, res, next) {
    console.log(`conditions: ${(!req.body)} ${(!req.body.uid)} ${(!req.body.provider)} ${JSON.stringify(req.body)}`);
    // This console.log appears as follows in the console once I make the request by Postman: false true true {}
    // But it receives what it shoulds with automated tests

    if (!req.body || !req.body.uid || !req.body.provider) { utilsErrors.handleNoParams(res); }
        else {
      /* ... There is a lot of code here but it's not relevant for the problem because it doesn't even reaches this point. */
    }
  })

module.exports = router

tests/users:

"use strict"
let request = require('supertest-as-promised');
const api = require('../app');
/* ... Another require not relevant for the problem ... */
request = request(api);

describe('Users route', function() {
  describe.only('POST /users', function() {
    it("should create a new user when it doesn't exist", function(done) {
      const params = {
        'appkey': helperCommon.appkey,
        'uid': 1,
        'provider': 'providerTest',
        'name': 'fakeName'
      };
      request
        .post('/users')
        .set('Accept', 'application/json')
        .send(params)
        .expect(201)
        .expect('Content-Type', /application\/json/)
        .then((res) => {
          expect(res.body).to.have.property('user');
          const userResponse = res.body.user;
          expect(userResponse).to.have.property('uid', params.uid);
          expect(userResponse).to.have.property('provider', params.provider);
          expect(userResponse).to.have.property('name', params.name);
          /* ... other expectectations that are not important for the problem ... */
          done();
        }, done)
    });
  });

Thanks!

Upvotes: 1

Views: 1971

Answers (1)

Fabio Carballo
Fabio Carballo

Reputation: 364

Make sure your are sending the POST request In postman as a x-www-form-urlenconded

Upvotes: 2

Related Questions