Tas Long
Tas Long

Reputation: 99

req.body is empty on POST with data, however logging req shows req.body exists

My problem

I am trying to write a register/login page in node.js using express.js. I have decided to split routes and app initialization into two files. When I send a POST request to localhost:3000/register with the data {"username":"xyz","password":"xyz"}, the request object has the attribute body. However when I try to access this attribute, I get undefined.

My current code

// app.js
// Load express and define port
const express = require('express');
const app = express();
const port = 3000;
// App Configurations
app.use(express.json())
// Load Routes
var registerRouter = require('./controllers/register.js');
// Use Routes
app.use('/register', registerRouter);
// Start App
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
// controllers/register.js
// requires
var argon2i = require('argon2-ffi').argon2i;
var bodyParser = require('body-parser');
var {Database, Model} = require('mongorito');
var crypto = require('crypto')
var Promise = require('bluebird');
var randomBytes = Promise.promisify(crypto.randomBytes);
var express = require('express');
// define router
var router = express.Router();
// Mongo Connection
const db = new Database('localhost/test', { 
    reconnectTries: 5 
});
// Models
class User extends Model {}
// Register Models
db.register(User);
// Routes
router.post('/', async (res, req) => {
    console.log(req.body);
    if(!req.body) return req.sendStatus(400); 
    const username = req.body.username;
    const salt = randomBytes(32); 
    const password = argon2i.hash(req.body.password, salt);
    var user = new User({
        username: username,
        password: password,
        salt: salt
    });
    await user.save;
    res.send("User Created");
});
// Disconnect From Database
db.disconnect;
//export router
module.exports = router;

My expected result

I expect to be able to access req.body and req.body.username.

Upvotes: 1

Views: 228

Answers (2)

Chukwuma Zikora
Chukwuma Zikora

Reputation: 109

I see you are importing bodyParser in controller/register but not setting it, at least in this snippet. if you do not have any special reasons for putting it in the controller, then do this instead.

// app.js
// Load express and define port
const express = require('express');
const bodyParser = require('body-parser'); // new code

const app = express();
app.use(bodyParser.urlencoded({ extended: true })); // new code
const port = 3000;
// App Configurations
app.use(express.json())
// Load Routes
var registerRouter = require('./controllers/register.js');
// Use Routes
app.use('/register', registerRouter);
// Start App
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Upvotes: 0

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

You have a small issue in you code. The router.post callback function first parameter is req and the second is res. The Callback function parameters are fixed not named parameters.

You are trying to get the body on the response object, though the name of the parameter is req but it still holds the response object. which is causing the issue.

Please change it.

Wrong:

router.post('/', async (res, req) => {

Correct:

router.post('/', async (req, res) => {

Upvotes: 1

Related Questions