gpt4 book ai didi

javascript - 如何从 angularjs/express 应用程序中的表单获取数据

转载 作者:太空宇宙 更新时间:2023-11-04 02:49:05 25 4
gpt4 key购买 nike

大家好,我可以知道如何从 angularjs/express 应用程序中的表单获取数据吗?例如

index.js 路由

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

handleSignup函数
有没有办法在不使用 req.body 的情况下获取数据?因为 angularjs 阻止我提交表单,所以我必须考虑另一种方式来获取数据。

 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 (有没有办法让页面在出现错误时保持在同一页面?如果没有错误则重定向到“/”)

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

我的表单

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

最佳答案

您似乎将 Angular 的单页应用程序 (SPA) 概念与传统的基于服务器的模型混淆了。使用 SPA,服务器不会执行任何重定向或提供 HTML。您的服务器发送 JSON,然后 Angular 在客户端渲染所有页面。

看起来请求对象没有正确传递到您的服务器端注册函数,这就是您无法访问 req.body 的原因。您的 Angular 代码看起来是正确的。

我将为您提供一些来 self 自己项目的代码,它们完全可以满足您的需求。

在你的index.js路由中

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

公共(public)目录中的 html 文件

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

最后是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;
});
}
});

我已经测试过它,只要您正确填写服务器端的所有注册逻辑,它也应该适合您。注意:为了使重定向正常工作,您需要设置 Angular 路由并创建一个要重定向到的页面。

关于javascript - 如何从 angularjs/express 应用程序中的表单获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20136368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com