Joshua Majebi
Joshua Majebi

Reputation: 1210

express receiving empty request body when receiving from angular 4 app

The body of the request being sent is empty according to req.body in my express route.

My main node file is as follows -

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

/*initializations*/
global.mongoose = require('mongoose');
mongoose.Promise = bluebird
global.app = express();
global.config = require('./config/config');
global.jwt = require('jsonwebtoken');
app.use(bodyParser.json({ type: 'application/json' }))
app.use(bodyParser.urlencoded({ extended: true }));//accept strings, arrays   and any other type as values
app.disable('x-powered-by');

require('./routes/auth.routes');

//DB connection
app.listen(config.port, function(){
 console.log("Express started on " +config.base_url +' in '+config.env +' environment. Press Ctrl + C to terminate');
 mongoose.connect(config.db.uri, config.db.options)
 .then(()=> { console.log(`Succesfully Connected to the Mongodb Database  at URL : `+config.db.uri)})
 .catch((error)=> { console.log(error)})
});

The auth.routes file has the signup route and this is where the req.body is empty but it does not hit the if statement that checks, but when i console.log(re.body), it gives me that - {}

app.post('/signup', function(req,res,next){

if (!req.body||req.body=={}){
    return res.status(400).send("Bad Request")
}

var user = new User(req.body);

user.password = bcrypt.hashSync(req.body.password, 10);

User.create(user, function(err,new_user){
    if (err) {
        console.log('A Big Error');
        return res.status(500).send("There was a problem registering the user.")
    }

   //success code       

  })
});

And the request from the angular 4 app is

signup(user:User):Observable<boolean>{

return this.http.post(this.signup_url,JSON.stringify(user), 
  {
    headers: new HttpHeaders().set('Accept', "application/json;q=0.9,*/*;q=0.8").set('Content-Type', "x-www-form-encoded")
  })
  .map((response: Response) => {
      if(response){
        if(response.json() && response.json().token&&response.json().user&&response.json().expires){
          this.setSession(response.json());
          return true;
        }
        else{
           return false;
        }  
      }
      else{
          return false;
      }
  });
}

I am certain the Angular 4 app is sending the right data to the server and that its not empty - checked chromes network request body.

I have tried the following links but none worked.

Express app empty request body with custom content type headers

Express receiving empty object

Node.js: Receiving empty body when submitting form.

Also tried with postman and the result is the same - which means the problem is from the express server and not the client side.

Upvotes: 3

Views: 1328

Answers (1)

YouneL
YouneL

Reputation: 8351

There is no need to stringify the posted data, the body-parser middleware will be responsible for parsing the data into object:

return this.http.post(this.signup_url, user, { ... }).map( ... );

One other thing, In the post handler, you might want to use .save() method instead of .create() because you already create a model instance, Remember that the .save() method is available on the model instance, while the .create() is called directly from the Model and takes the object as a first parameter

Example with .save() method:

app.post('/signup', function(req,res,next) {

    if (!req.body){
        return res.status(400).send("Bad Request");
    }

    var user = new User(req.body);

    var salt = bcrypt.genSaltSync(saltRounds);
    user.password = bcrypt.hashSync(req.body.password, salt);

    user.save(function( err ) {
        if (err) {
            console.log('A Big Error');
            return res.status(500).send("There was a problem registering the user.");
        }

        //success code       
        res.json({ success: true });
    })
});

Example with .create() method:

router.post('/signup', function(req,res,next){

    if (!req.body){
        return res.status(400).send("Bad Request")
    }

    var salt = bcrypt.genSaltSync(saltRounds);
    req.body.password = bcrypt.hashSync(req.body.password, salt);

    User.create ( req.body, function( err,  new_user) {
        if (err) {
            console.log('A Big Error');
            return res.status(500).send("There was a problem registering the user.")
        }

        //success code       
        res.json({ success: true });
    });
});

Upvotes: 3

Related Questions