EmberJS空的req身体

时间:2017-01-03 15:20:05

标签: node.js express ember.js ember-data

我是EmberJS的新手,我尝试使用nodejs和expressjs作为后端将一些数据保存到Amazon DynamoDB,但是当我通过EmberJS提交表单时我得到一个空的req body

如果我使用curl尝试,如下所示,我可以成功保存数据,因此这表明后端工作正常。

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

我尝试在application.js JSONAPIAdapter中设置Content-Type header但没有运气。我也尝试使用REST适配器,也没有运气。

以下是我的代码:

前端 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'),
});

模板 - 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">
                    {{input name="firstName" name="firstName" type="text" value=model.firstName class="validate" required="required" aria-required="true"}}
                    <label for="firstName">First Name</label>
                </div>
                <div class="input-field col s6">
                    {{input name="lastName" name="lastName" type="text" value=model.lastName class="validate" required="required" aria-required="true"}}
                    <label for="lastName">Last Name</label>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s6">
                    {{input type="email" value=model.email name="email" class="validated" }}
                    <label for="email">Email</label>
                </div>
                <div class="input-field col s6">
                    {{input name="password" name="password" type="password" value=model.password class="validate" required="required" aria-required="true"}}
                    <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" {{action 'register'}} >Register Me!</button>
        </div>
        <div class="col s6 m6 l6">
            {{#link-to 'main'}}<a href="" class="waves-effect waves-light center-align btn col s6 m6 l6 teal darken-1">Cancel</a>{{/link-to}}
        </div>
    </div>
</div>

路线 - 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');
            });
        },
    }   
});

后端 - 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 = 'https://www.myserserver.com';
}
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;

路线 - 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);
};

当我使用EmberJS发送数据时,这是req.body的console.log:

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

我在这里缺少什么?

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

让它运行起来。 对于那些面临同样问题的人,我只需用我的register动作取代:

register: function() {
  var _this = this;

  this.get('model').save()
    .then(function(data) {
        console.log('signup response:', data);
        alert('signup saved ok! redirect to signin');
        _this.transitionToRoute('main');
    }, 
    function(data) {
        alert('signup saved fail!');
        _this.set('error', data.responseJSON.error || 'sorry, signup failed.');
    });
}