最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to get data from a form in angularjsexpress app - Stack Overflow

programmeradmin1浏览0评论

Hi guys may i know how to get data from a form in angularjs/express app ? for example

index.js routes

app.post('/register', sessionHandler.handleSignup);

handleSignup function
is there any way to get the data without using req.body ? because angularjs prevent me submit the form so i have to think another way to get the data.

 this.handleSignup = function(req, res, next) {
        "use strict";

        var email = req.body.email,
         confirmEmail = req.body.confirmEmail,
         password = req.body.password,
         confirmPassword = req.body.confirmPassword,
         firstName = req.body.firstName,
         lastName = req.body.lastName,
         penName = req.body.penName,
         publicUsername = req.body.publicUsername;

        // set these up in case we have an error case
        var errors = {'email': email,'publicUsername': publicUsername,'firstName': firstName,'lastName': lastName,'penName': penName};
        if (validateSignup(publicUsername, password, confirmPassword, email, confirmEmail, errors)) {
            users.addUser(email, password, firstName, lastName, penName, publicUsername, function(err, user) {
                "use strict";

                if (err) {
                    // this was a duplicate
                    if (err.code == '11000') {
                        errors['email_error'] = "Email already in use. Please choose another";
                        return res.render("register", errors);
                    }
                    // this was a different error
                    else {
                        return next(err);
                    }
                }

                sessions.startSession(user['_id'], function(err, session_id) {
                    "use strict";

                    if (err) return next(err);

                    res.cookie('session', session_id);
                    return res.redirect('/');
                });
            });
        } else {
            console.log("user did not validate");
            return res.render("register", errors);
        }
    }

controller ( is there any way to make the page stay at the same page if there is an error ? if no error then redirect to "/")

function RegisterCtrl($scope, $http, $location) {
  $scope.form = {};
  $scope.submitPost = function() {
    $http.post('/register', $scope.form).
      success(function(data) {
        $location.path('/');
      });
  };
}

my form

<div class="pure-u-1 text-center">
  <form method="post" class="pure-form pure-form-aligned">
    <fieldset>
      <legend><h1 class="pure-splash-subhead midnightblue"><span class='lightblue'>Join</span> us today and start write things that <span class='maroon'>matter</span></h1>
      </legend>
      <p class="text-center red">{{email_error}}</p>
      <div class="pure-control-group">
        <label for="email">Email Address</label>
        <input required name="email" ng-model="form.email" class="pure-u-1-3" type="email" placeholder="Email Address">
      </div>
      <div class="pure-control-group">
        <p class="text-center red">{{confirmEmail_error}}</p>
        <label for="confirmEmail">Confirm Email Address</label>
        <input required name="confirmEmail" ng-model="form.confirmEmail" class="pure-u-1-3" type="email" placeholder="Confirm Email Address">
      </div>
      <div class="pure-control-group">
        <p class="text-center red">{{password_error}}</p>
        <label for="password">Password</label>
        <input required name="password" ng-model="form.password" class="pure-u-1-3" type="password" placeholder="Password">
      </div>
      <div class="pure-control-group">
        <p class="text-center red">{{confirmPassword_error}}</p>
        <label for="confirmPassword">Confirm Password</label>
        <input required name="confirmPassword" ng-model="form.confirmPassword" class="pure-u-1-3" type="password" placeholder="Confirm Password">
      </div>
      <br/><br/>
      <div class="pure-control-group">
        <label for="firstName">First Name</label>
        <input required name="firstName" class="pure-u-1-3" ng-model="form.firstName" type="text" placeholder="Your first name">
      </div>
      <div class="pure-control-group">
        <label for="lastName">Last Name</label>
        <input required name="lastName" class="pure-u-1-3" ng-model="form.lastName" type="text" placeholder="and your last name">
      </div>
      <div class="pure-control-group">
        <label for="penName"><abbr title="A pen name">Nom de plume</abbr></label>
        <input required name="penName" ng-model="form.penName" class="pure-u-1-3" type="text" placeholder="Pen Name eg:J.R.R. Tolkien">
      </div>
      <div class="pure-control-group">
        <label for="publicUsername">Public Username</label>
        <input required name="publicUsername" class="pure-u-1-3" type="text"  ng-model="form.publicUsername" placeholder="Username eg:gandalf">
        <p class="pure-splash-subhead">/@<b class="maroon">{{form.publicUsername}}</b></p>
        <p class="text-center red">{{publicUsername_error}}</p>
      </div>
      <div class="pure-u-1 ">
        <label for="conAndTerm" class="pure-checkbox">
          <input id="conAndTerm" type="checkbox"> I've read the <a class='link blue'href="#">terms and conditions</a>
        </label>
        <br/>
        <input type='submit' ng-click="submitPost()" class="pure-button pure-button-secondary pure-u-1-3" value="Register">
        <br/>
      </div>
    </fieldset>
  </form>
</div>

Hi guys may i know how to get data from a form in angularjs/express app ? for example

index.js routes

app.post('/register', sessionHandler.handleSignup);

handleSignup function
is there any way to get the data without using req.body ? because angularjs prevent me submit the form so i have to think another way to get the data.

 this.handleSignup = function(req, res, next) {
        "use strict";

        var email = req.body.email,
         confirmEmail = req.body.confirmEmail,
         password = req.body.password,
         confirmPassword = req.body.confirmPassword,
         firstName = req.body.firstName,
         lastName = req.body.lastName,
         penName = req.body.penName,
         publicUsername = req.body.publicUsername;

        // set these up in case we have an error case
        var errors = {'email': email,'publicUsername': publicUsername,'firstName': firstName,'lastName': lastName,'penName': penName};
        if (validateSignup(publicUsername, password, confirmPassword, email, confirmEmail, errors)) {
            users.addUser(email, password, firstName, lastName, penName, publicUsername, function(err, user) {
                "use strict";

                if (err) {
                    // this was a duplicate
                    if (err.code == '11000') {
                        errors['email_error'] = "Email already in use. Please choose another";
                        return res.render("register", errors);
                    }
                    // this was a different error
                    else {
                        return next(err);
                    }
                }

                sessions.startSession(user['_id'], function(err, session_id) {
                    "use strict";

                    if (err) return next(err);

                    res.cookie('session', session_id);
                    return res.redirect('/');
                });
            });
        } else {
            console.log("user did not validate");
            return res.render("register", errors);
        }
    }

controller ( is there any way to make the page stay at the same page if there is an error ? if no error then redirect to "/")

function RegisterCtrl($scope, $http, $location) {
  $scope.form = {};
  $scope.submitPost = function() {
    $http.post('/register', $scope.form).
      success(function(data) {
        $location.path('/');
      });
  };
}

my form

<div class="pure-u-1 text-center">
  <form method="post" class="pure-form pure-form-aligned">
    <fieldset>
      <legend><h1 class="pure-splash-subhead midnightblue"><span class='lightblue'>Join</span> us today and start write things that <span class='maroon'>matter</span></h1>
      </legend>
      <p class="text-center red">{{email_error}}</p>
      <div class="pure-control-group">
        <label for="email">Email Address</label>
        <input required name="email" ng-model="form.email" class="pure-u-1-3" type="email" placeholder="Email Address">
      </div>
      <div class="pure-control-group">
        <p class="text-center red">{{confirmEmail_error}}</p>
        <label for="confirmEmail">Confirm Email Address</label>
        <input required name="confirmEmail" ng-model="form.confirmEmail" class="pure-u-1-3" type="email" placeholder="Confirm Email Address">
      </div>
      <div class="pure-control-group">
        <p class="text-center red">{{password_error}}</p>
        <label for="password">Password</label>
        <input required name="password" ng-model="form.password" class="pure-u-1-3" type="password" placeholder="Password">
      </div>
      <div class="pure-control-group">
        <p class="text-center red">{{confirmPassword_error}}</p>
        <label for="confirmPassword">Confirm Password</label>
        <input required name="confirmPassword" ng-model="form.confirmPassword" class="pure-u-1-3" type="password" placeholder="Confirm Password">
      </div>
      <br/><br/>
      <div class="pure-control-group">
        <label for="firstName">First Name</label>
        <input required name="firstName" class="pure-u-1-3" ng-model="form.firstName" type="text" placeholder="Your first name">
      </div>
      <div class="pure-control-group">
        <label for="lastName">Last Name</label>
        <input required name="lastName" class="pure-u-1-3" ng-model="form.lastName" type="text" placeholder="and your last name">
      </div>
      <div class="pure-control-group">
        <label for="penName"><abbr title="A pen name">Nom de plume</abbr></label>
        <input required name="penName" ng-model="form.penName" class="pure-u-1-3" type="text" placeholder="Pen Name eg:J.R.R. Tolkien">
      </div>
      <div class="pure-control-group">
        <label for="publicUsername">Public Username</label>
        <input required name="publicUsername" class="pure-u-1-3" type="text"  ng-model="form.publicUsername" placeholder="Username eg:gandalf">
        <p class="pure-splash-subhead">https://www.HoneyBooBoo./@<b class="maroon">{{form.publicUsername}}</b></p>
        <p class="text-center red">{{publicUsername_error}}</p>
      </div>
      <div class="pure-u-1 ">
        <label for="conAndTerm" class="pure-checkbox">
          <input id="conAndTerm" type="checkbox"> I've read the <a class='link blue'href="#">terms and conditions</a>
        </label>
        <br/>
        <input type='submit' ng-click="submitPost()" class="pure-button pure-button-secondary pure-u-1-3" value="Register">
        <br/>
      </div>
    </fieldset>
  </form>
</div>
Share Improve this question edited Mar 31, 2016 at 4:47 Mosh Feu 29.4k18 gold badges93 silver badges141 bronze badges asked Nov 22, 2013 at 3:15 John LimJohn Lim 3,1095 gold badges33 silver badges41 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

It seems you are confusing Angular's single-page-app (SPA) concept with the traditional server based model. With an SPA, the server doesn't do any redirecting or serve HTML. Your server sends JSON, and Angular then renders all the pages client-side.

It looks likely that the request object is not being passed correctly to your server-side registration function, and that is why you cannot access req.body. Your Angular code looks correct.

I am going to give you some code from my own project that does exactly what you want.

Inside your index.js routes

var signup = require('./routes/signup');
app.post('/signup', function(req, res) {
    signup(req, res);
});

routes/signup.js

module.exports = function (req, res) {
  validateSignup(req.body, function(error, data) {
    if(error) {
      res.send(400, error.message);
    } else {
      res.send(JSON.stringify(data));
    }
  })
}

function validateSignup(data, callback) {
  // All your validation logic goes here
  if(success) callback(null, newuser);
  else callback(new Error('Registration failed!'), null);
}

Your html file in the public directory

<!DOCTYPE html>
<html lang="en" ng-app="app">
  <head>
    <title>Sample Registration Page</title>
    <link href="styles/bootstrap.css" rel="stylesheet">
    <link href="styles/signin.css" rel="stylesheet">
  </head>
  <body>
    <div class="container" ng-controller="SignupCtrl">
      <div class="alert alert-danger" ng-if="errorMessage">{{errorMessage}}</div>
      <form class="form-signin">
        <h2 class="form-signin-heading">Register</h2>
        <input type="text" class="form-control" name="username" placeholder="Username" ng-model="User.username" required autofocus>
        <input type="password" class="form-control" name="password" placeholder="Password" ng-model="User.password" required>
        <button class="btn btn-lg btn-primary btn-block" ng-click="register()">Register</button>
      </form>
    </div> <!-- /container -->
    <script type="application/javascript" src="lib/angular/angular.min.js"></script>
    <script type="application/javascript" src="scripts/controllers/register.js"></script>
  </body>
</html>

And finally register.js

angular.module('app', [])
.controller('SignupCtrl', function ($scope, $http, $location) {

  $scope.User = {};
  $scope.errorMessage = '';

  $scope.register = function() {
    $http.post('/signup', $scope.User).
    success(function(data) {
      $location.path('/');
    }).error(function(err) {
      $scope.errorMessage = err;
    });
  }
});

I've tested it, and as long as you fill in all your signup logic on the server-side correctly, it should work for you also. Note: for the redirect to work properly, you will need to set up your Angular routing and create a page to redirect to.

in your angular controller you can use the data inside ng-model="form.email" with $scope.form.email

then you can send that to your nodejs app with a http request or other like websockets.

You need to define ng-app in your app. Then to handle the data use ng-model.

your template input field should have the data model to handle the data.

Like for email

<input required name="email" class="pure-u-1-3" type="email" placeholder="Email Address" ng-model="form.email">
发布评论

评论列表(0)

  1. 暂无评论