question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

req.body empty and or undefined

See original GitHub issue

Hello guys,

I am currently working on an authentication api using express and body-parser. But I ran into problems with the parser.

For example, here is my app.js:

var morgan = require('morgan');
var bodyParser = require('body-parser');
var passport = require('passport');
var express = require('express');


var app = express();


app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ type: 'application/*+json' }));


app.use(morgan('dev'));



app.use(passport.initialize());
require('./config/passport')(passport);

var routes = require('./routes/index');
var register = require('./routes/register');
var authenticate = require('./routes/authenticate');
var dashboard = require('./routes/dashboard');

app.use('/', routes);
app.use('/register', register);
app.use('/authenticate', authenticate);
app.use('/dashboard', dashboard);



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

// error handlers

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

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


module.exports = app;

Now let’s have a look at the register.js, located in routes/register.js:

var express = require('express');
var router = express.Router();




router.post('/', function (req, res, next) {
    if (!req.body.email || !req.body.password) {
        console.log(req.body);
        console.log(req.body.email);
        res.json({success: false, message: 'Please enter email and password.'});
    } else {
        var newUser = new User({
            email: req.body.email,
            password: req.body.password
        });

        // Attempt to save the user
        newUser.save(function (err) {
            if (err) {
                return res.json({success: false, message: 'That email address already exists.'});
            }
            res.json({success: true, message: 'Successfully created new user.'});
        });
    }
});

module.exports = router;

I am currently sending JSON by using HttpRequester or RESTClient. No matter which one. Both will bring the same bug? I have been printing out “req.body” and “req.body.email” for example.

Case 1: POST http://localhost:3000/register Content-Type: application/json { "email":"testmail@test.com", "password":"123456" } Outputs: {} undefined POST /register 200 0.350 ms - 62

Case 2 Same with url-encoded POST http://localhost:3000/register Content-Type: application/x-www-form-urlencoded { "email":"testmail@test.com", "password":"123456" } Outputs: { '{\n"email":"testmail@test.com",\n"password":"123456"\n}': '' } undefined POST /register 200 1.756 ms - 62 But why undefined?

Case 3 Working like normal post parameters POST http://localhost:3000/register Content-Type: application/x-www-form-urlencoded email=testmail@test.com Outputs: { email: 'testmail@test.com' } testmail@test.com POST /register 200 1.502 ms - 62 I personally don’t know why it is not parsing the json object. Maybe you know an answer?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
dougwilsoncommented, Oct 7, 2016

I think the issue is from your type: 'application/*+json' above. What are you trying to achieve with that?

1reaction
3HMonkeycommented, Oct 7, 2016

Hello and thank you for your quick answer.

I used type: 'application/*+json' for testing purposes. By the way, it seems that just bodyParser.json() ignores the JSON sent because with the empty bodyParser.json() I am getting an “no view engine error” , so I tried out the different settings which are documented like the setting of the type.

That means: Using:

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ type: 'application/*+json' }));

brings: application/x-www-form-urlencoded filled body - undefined body.email application/json empty body - undefined body.email text/plain empty body - undefined body.email text/html empty body - undefined body.email

Using:

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

brings: application/x-www-form-urlencoded filled body - undefined body.email application/json empty body - “No default engine” error text/plain empty body - undefined body.email text/html empty body - undefined body.email

It also seems that there is no difference between: app.use(bodyParser.urlencoded({ extended: false })); and app.use(bodyParser.urlencoded({ extended: true})); in my case. Or swapping urlencoded with json.

UPDATE: I found out that if I use x-www-form-urlencoded the body-parser tries to doubleparse that object: { '{\n"email":"test@test.com",\n"password":"123456",\n"test":"123456"\n}': '' } Here is a small workaround for this:

try{req.body = JSON.parse(Object.keys(req.body)[0])}catch(err){req.body = req.body}

But this is not really what was intended because I want to use the bodyParser.json() and not an use x-www-form-urlencoded workaround to work with json objects.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Express.js req.body undefined - Stack Overflow
I was using Postman for Chrome to test a JSON api built in REST, but the object received by Express was empty every...
Read more >
How can req.headers and req.body be undefined in node.js?
js application sits behind an nginx reverse proxy. Sometimes both req. headers and req. body are undefined.
Read more >
Can not get parameter from req.body with POST request in ...
Every time I post a request with body data (example: ... on local but in Windows Azure NodeJS AppService, uid is always Undefined...
Read more >
express request body undefined - You.com | The AI Search ...
node js express post request body undefined ... a issue during post request empty goes undefined on proxy server endpoint i don't know...
Read more >
5.x API - Express.js
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found