mardi 3 janvier 2017

EmberJS empty req body

I am new to EmberJS and I'm trying to save some data to Amazon DynamoDB using nodejs and expressjs as back-end but I'm getting a empty req body when submit my form through EmberJS.

If I try it using curl, as follows, I can save the data successfully, hence this shows that the back-end is working properly.

curl --header "Content-Type: application/json" --data '{"user":{"email":"teste@teste.com","firstName":"teste","lastName":"last name","password":"teste"}}' http://localhost:3000/api/users

I tried to set the Content-Type header in the application.js JSONAPIAdapter but got no luck. I also tried to use a REST adapter and got no luck also.

Following is my code:

Front-end model - user.js

import DS from 'ember-data';

export default DS.Model.extend({
    email: DS.attr('string'),
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    password: DS.attr('string'),
});

template - register.hbs

<div class="container" style="margin-top: 30px;">
    <div class="row">
        <form  class="col s12" name="registerForm" id="registerForm">
            <div class="row">
                <div class="input-field col s6">
                    
                    <label for="firstName">First Name</label>
                </div>
                <div class="input-field col s6">
                    
                    <label for="lastName">Last Name</label>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s6">
                    
                    <label for="email">Email</label>
                </div>
                <div class="input-field col s6">
                    
                    <label for="password">Password</label>
                </div>
            </div>
        </form>
    </div>
    <div class="row">
        <div class="col s6 m6 l6">
            <button class="waves-effect waves-light center-align btn col s6 m6 l6 teal darken-1"  >Register Me!</button>
        </div>
        <div class="col s6 m6 l6">
            <a href="" class="waves-effect waves-light center-align btn col s6 m6 l6 teal darken-1">Cancel</a>
        </div>
    </div>
</div>

route - register.js

import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return this.store.createRecord('user');
    },

    actions: {      
        willTransition() {
          // rollbackAttributes() removes the record from the store
          // if the model 'isNew'
          this.controller.get('model').rollbackAttributes();
        },  

        register() {
            let email = this.controller.get('model.email');
            let firstName = this.controller.get('model.firstName');
            let lastName = this.controller.get('model.lastName');
            let password = this.controller.get('model.password');

            let user = {
                email: email,
                firstName: firstName,
                lastName: lastName,
                password: password
            };

            console.log('USER === ' + JSON.stringify(user));

            const newUser = this.store.createRecord('user', {
                user
            });

            newUser.save().then((response) => {
                alert('Registro efetuado com sucesso ! ID = ' + response.get('id'));
                this.set('email', '');
                this.set('firstName', '');
                this.set('lastName','');
                this.set('password','');

                this.transitionTo('main');
            });
        },
    }   
});

Back-end - NodeJS + ExpressJS

app.js

var express = require('express');

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

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

console.log('ENV = ' + process.env.NODE_ENV);

var cors;

if (process.env.NODE_ENV == 'production') {
   cors = 'http://ift.tt/2iz9RvJ';
}
else {
  cors = 'http://localhost:4200';
}

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', cors);

  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  next();
});

var globSync          = require('glob').sync;
var routes            = globSync('./routes/*.js', { cwd: __dirname}).map(require);

var ddb = require('dynamodb').ddb(
        { 
            accessKeyId: 'XXXXX',
            secretAccessKey: 'ZZZZZZZ',
            endpoint: 'dynamodb.eu-west-1.amazonaws.com'
    });

routes.forEach( function(route) { 
    route(app, ddb);
});

module.exports = app;

route - users.js

var express = require('express');
var uuid    = require('node-uuid');
var crypto  = require('crypto');

module.exports = function(app, client) {
    var router = express.Router();

    var options = { attributesToGet: ['nome'],
                    consistentRead: true
                  };    

    router.get('/users',function(req, res, next){
        client.scan('users', {}, function(err, data) {
            if(err) {
                return res.status(200).json({"erro": err});
            } 
            else {
                res.send({user:data.items});
            }
        });
    });    

    router.post('/users',function(req, res, next) {
        var payload = req.body.user;

        console.log('\n REQ BODY = ' + JSON.stringify(req.body) + '\n\n');

        var response = '';

        var id = uuid.v1();
        var salt = crypto.randomBytes(16).toString('hex');

        var password = payload.password; //req.body.password;

        var hash = crypto.pbkdf2Sync(password, salt, 1000, 64,'sha512').toString('hex');

        var firstName = payload.firstName;
        var lastName = payload.lastName;
        var email = payload.email;

        var user = {
            id: id,
            email: email,
            firstName: firstName,
            lastName: lastName,
            hash: hash,
            salt: salt
        }        

        console.log(user);

        client.putItem('users', user, {}, function(err, res, cap) {
            if (err) {
              this.response = ('erro = ' + err);
            }
            else {
              //console.log('PutItem: ' + cap);
              console.log(res);
              //this.response = ('User registered!');
            }
        });

        return res.status(200);
    });

    app.use('/api', router);
};

This is the console.log for req.body when I send the data using EmberJS:

REQ BODY = {"user":{"email":null,"firstName":null,"lastName":null,"password":null}}

What am I missing here?

Thanks very much for the help!




Aucun commentaire:

Enregistrer un commentaire