Timbo
Timbo

Reputation: 487

req.body is always undefined

I know this question has been asked and answered already. Though, I have followed all the advice and done it the way I am supposed to but it still does not work for me.

Here is my app.js:

const express      = require('express');
const bodyParser   = require('body-parser');
const cors         = require('cors');

const app = module.exports = express();

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

Here is my server.js:

const server = require('./dependencies/app');
const connectionHelper = require('./databaseOperations/connectionHelper');
const process =  require('process');
const routes = require("./routes");

connectionHelper.establishConnection;

process.on('exit', function ()
{
    connectionHelper.closeConnection;
});

routes(server);

server.listen(3000);

Here is my routes.js:

const tweetHandler = require("./handler/tweetHandler");
const userHandler = require("./handler/userHandler");

let createRoutes = function(app)
{
    app.post('/submitTweet', tweetHandler.handleTweet);
    app.get('/login', userHandler.login);
}

module.exports = createRoutes;

Finally the twitter handler that throws the error:

const Tweet = require("../schema/tweetSchema");


module.exports = {
    handleTweet: function (res, req)
        {
            console.log(req.body);
            if (req.body.topic && req.body.tweet) {
                let tweet = new Tweet({topic: req.body.topic, tweet: req.body.tweet});

                let promise = tweet.save();

                promise.then(function (result) {
                    console.log("Result ", result);
                    res.status(200).send({message: "Tweet was successfully submitted"});
                })
            }
            else {
                res.status(401).send({message: "You need to provide a topic as well as a tweet"});
            }
        }
    };

The error I am getting is: TypeError: Cannot read property 'topic' of undefined

I am really not understanding my error here and I am sure it is something really dumb.

I am testing with postman and yes I use the x-www-form-urlencoded option.

Can someone please tell me what I am missing?

The other issue I am having is that res.status is not being recognised as a function. All function calls on either req or res throw an error if you can answer that too that would be amazing!

Upvotes: 0

Views: 428

Answers (1)

Marian
Marian

Reputation: 4079

Change function (res, req) to function(req, res). Request comes first, and then you send out response - an easy way to remember. Also q is before s alphabetically.

As for the reason you get undefined body - well, since response is still pristine at that point of time, it's body is undefined

Upvotes: 7

Related Questions