我是angularJs中的新手,我试图用angularJS和nodejs(服务器端)进行基本登录,我现在不关心安全性我只是想学习如何发布。所以我创建了一个登录表单和一个带角度的控制器:
我的登录表格:
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="login.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="login.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login()">Login</button>
</div>
</form>
</div>
然后我的路由器&amp;控制器Angularjs:
'use strict';
angular.module('login', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl'
});
}])
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.login = function() {
$http.post('/api/users/login', $scope.login).success(function (response) {
console.log(response);
// refresh();
});
};
}]);
和服务器端我有:
router.post('/login/', function(req, res) {
// here "/login/" means "/users/login" ( in index of controllers)
console.log(req.body.mail);
var usermail = req.body.mail;
var pass = req.body.password;
console.log(usermail + pass);
User.find({mail: usermail}, function(err, user) {
if (err) {
res.send(err);
console.log("ça marche pas")
} else {
res.json( user );
console.log(user);
}
})
});
服务器端:它工作(当我使用DHC chrome扩展到Post)但是当我使用angularjs视图时我得到了这个错误:
POST http://localhost:3000/api/users/login 400(错误请求)
请帮我解决,我想我错过了什么。提前谢谢。
答案 0 :(得分:1)
我认为您正在发送登录功能,如下所示:
$http.post('/api/users/login', $scope.login)
您可能希望在登录功能中传递一个可以发送到服务器的参数,如下所示:
$scope.login = function(loginData) {
$http.post('/api/users/login', loginData).success(function (response)
<强>更新强>
您正在将表单值分配给$ scope.login。如果你要为它创建一个单独的变量,例如loginForm,你可以将它作为有效的JSON发送到你的API:
<div class="col-md-4">
<h1>Login</h2>
<form class="form" >
<div class="form-group">
<label>Username</label>
<input type="email" class="form-control" ng-model="loginForm.mail" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" ng-model="loginData.password" required>
</div>
<div>
<button type="text" class="btn btn-default" ng-click="login(loginData)">Login</button>
</div>
</form>
</div>
和.js:
.controller('loginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.loginForm = {
mail: '',
password: ''
};
$scope.login = function(loginData) {
// Check what this prints out:
console.log(loginData);
$http.post('/api/users/login', loginData).success(function (response) {
console.log(response);
// refresh();
});
};
}]);