0

I am trying to create a simple API to create different objects called entities and store them in a mongo database. I've been following the tutorial here and updating it for my own use. I'm using mongoose as well to communicate with the database, but I'm running into an issues where whenever I try and do a POST request, it returns an error due to the fact that req.body.content is undefined. Here is my server.js file:

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

// create express app
var app = express();

// parse requests of content-type - application/x-www-form-urlencoded
app.use( bodyParser.urlencoded( { extended: true } ) );

// parse requests of content-type - application/json
app.use( bodyParser.json() );

// database requirements
var dbConfig = require( './config/database.config.js' );
var mongoose = require( 'mongoose' );

// Configuring database
mongoose.Promise = global.Promise;

mongoose.connect( dbConfig.url );

mongoose.connection.on( 'error', function()
    {   
        console.log( "Could not connect to the database. Exiting now..." );
        process.exit();
    }   
);

mongoose.connection.once( 'open', function()
    {   
        console.log( "Successfully connected to the database" );
    }   
);

// define a simple route
app.get( '/', function( req, res ) 
    {   
        res.json( { "message" : "Welcome to API. More to come soon...." } );
    }   
);

// Require Entities routes
require( './app/routes/entity.routes.js' )( app );  

// listen for requests
app.listen( 3000, function()
    {   
        console.log( "Server is listening on port 3000" );
    }   
);

This is my external routes.js file:

module.exports = function( app ) { 

   var entities = require( '../controllers/entity.controller.js' );

    // Create a new Entity
    app.post( '/entities', entities.create );

    // Retrieve all Entities
    app.get( '/entities', entities.findAll );

    // Retrieve a single Entity with entityId
    app.get( '/entities/:entityId', entities.findOne );

    // Update an Entity with entityId
    app.put( '/entities/:entityId', entities.update );

    // Delete an Entity with entityId
    app.delete( '/entities/:entityId', entities.delete );

}

My controller.js file as well:

var Entity = require( '../models/entity.model.js' );

exports.create = function( req, res ) 
{

    // create and save a new entity
    console.log( 'req.body: ' + req.body );
    if( !req.body.content ) 
    {   
        console.log( 'req.body.content: ' + req.body.content );

        return res.status( 400 ).send( { message: "Entity can not be empty" } );
    }   

    var entity = new Entity
    ({    
        filename       : req.body.filename, 
        material       : req.body.material,
        design_element : req.body.design_element, 
        style          : req.body.style

    }); 

    entity.save( function( err, data ) 
    {   
        if( err ) 
        {   
            console.log( err );

            res.status( 500 ).send( { message: "Some error occurred while creating the Entity." } );

        }   
        else 
        {   
            res.send( data );
        }   
    }); 

};

And an image of my post request as well. I am using Postman to test my request.Post Request Result

I found some stackoverflow posts already like the one here that says to set any app.use() functions before defining any routes, and made sure that body-parser was installed, but I still get the error. Any help would be greatly appreciated.

Thanks!

ans
  • 141
  • 15
  • can you show the code where you are attempting this post request? – Chaim Friedman Mar 12 '18 at 18:09
  • I've updated my post to include my post request attempt. I'm using Postman. – ans Mar 12 '18 at 18:14
  • I think Chaim is asking for the code in `entity.routes.js'` – MindlessRouse Mar 12 '18 at 18:41
  • Gotcha. I've updated the post to include my controller and routes.js code as well. – ans Mar 12 '18 at 18:46
  • in your postman screenshot it seems your sending the response raw, can you try form-url-encoded? – Chaim Friedman Mar 12 '18 at 19:05
  • I think you need to pass your parameter object as ` { content : { filename: ...} } ` . You are trying to access content from request body which is not there. also then you will need to access other params as `req.body.content.filename` while creating an entity – zerosand1s Mar 12 '18 at 19:06
  • @ChaimFriedman I tried doing a form-url-encoded and got the same error stating: "Entity can not be empty" – ans Mar 12 '18 at 19:11
  • ok one final thought. Can you please show what your `console.log(req.body)` prints? – Chaim Friedman Mar 12 '18 at 19:13
  • @HarshalGangurde I put the data inside a content block of the json and got a different error. You can see an image of the error [here](https://imgur.com/a/M1z50) – ans Mar 12 '18 at 19:17
  • @ans maybe try "content" just like other json keys – zerosand1s Mar 12 '18 at 19:19
  • @ChaimFriedman Here is a print out of `req.body` and `req.body.content`: `Server is listening on port 3000 Successfully connected to the database req.body: [object Object] req.body.content: undefined` – ans Mar 12 '18 at 19:19
  • @HarshalGangurde So I did that and strangely it looks like it created an object, but with nothing except an _id and __v value. You can see the post and the result [here](https://imgur.com/a/3mpfY) – ans Mar 12 '18 at 19:29
  • 1
    @ans ok so creating a `content` object makes sense if you are passing data the way you were doing it before i.e. `raw` and type of data `JSON` as per screenshots in the question. If you are passing parameters as `x-www-form-urlencoded` you don't need to send extra content object as per your latest screenshot. Just pass those four params and may be check for `(!req.body.filename)` to return an error – zerosand1s Mar 12 '18 at 19:52
  • @HarshalGangurde Interesting! So it seems that all the fields are blocked out, yet content is undefined, which is why that error get's thrown. You can view the results [here](https://imgur.com/a/do8q6) on the server side. Thank you for the help, I see where my dumb mistake was!!! – ans Mar 12 '18 at 20:09
  • @ans yes exactly. I am not sure what standard you are talking about when you say _accessing through `req.body.content`_. You can access params like `req.body.param` just the way you are doing while creating a new entity. If you want to use `content` object you will have to explicitly pass it in your request – zerosand1s Mar 12 '18 at 20:18
  • You can disregard that comment, I was thinking content was set automatically, I see what you mean by having to pass it through explicitly. – ans Mar 12 '18 at 20:19
  • @ans yep, glad that helped – zerosand1s Mar 12 '18 at 20:22

0 Answers0