简体   繁体   中英

how to get data from a form in angularjs/express app

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.com/@<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>

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">

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM