Trying to post from a register form in a MEAN application, I can use Postman to successfully post using x-www-form-urlencoded, but the request body in the app is empty when I console.log it. The register form (part):
<form class="form-horizontal" ng-submit="register.saveUser()">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="user.userData.name">
api.js (part)
var bodyParser = require('body-parser'); // get body-parser
var User = require('../models/user');
var jwt = require('jsonwebtoken');
var config = require('../../config');
var superSecret = config.secret;
module.exports = function(app, express) {
var apiRouter = express.Router();
apiRouter.post('/register', function(req, res) {
var user = new User();
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
console.log(req.body); //EMPTY
I have app.use bodyParser in server.js before the call to api.js
server.js (part)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var apiRoutes = require('./app/routes/api')(app, express);
app.use('/api', apiRoutes);
I'm doing something wrong but can't see what.
Added for @mscdex: register.saveUser() refers to userRegisterController saveUser() function:
.controller('userRegisterController', function(User) {
var vm = this;
// function to create a user
vm.saveUser = function() {
vm.processing = true;
vm.message = '';
// use the register function in the userService
User.register(vm.userData)
.success(function(data) {
vm.processing = false;
vm.userData = {};
vm.message = data.message;
});
};
This uses the userService register function:
// register a user
userFactory.register = function(userData) {
return $http.post('/api/register/', userData);
};
This calls api file which I have posted above.
BTW when I use Postman the console.dir(req.headers['content-type']) shows 'application/x-www-form-urlencoded' and is successful.
I spent quite a few hours on this today and ultimately the problem of 'undefined' being received by the apiRouter function was due to my use of
<input type="text" class="form-control" ng-model="user.userData.name">
whereas I should have used
<input type="text" class="form-control" ng-model="register.userData.name">
because I had used
.when('/register', {
templateUrl: 'app/views/pages/register.html',
controller: 'userCreateController',
controllerAs: 'register'
});
in the apiRoutes file. I'm still learning the usage of ControllerAs in this context.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.