发表angularjsforms到nodejs Express(Bad request)
即时通讯新的angularJs,即时尝试做一个基本的login与angularJS和nodejs(服务器端),我不在乎安全现在我只是想学习如何发布。 所以我做了一个login表单和一个angular度控制器:
我的login表单:
<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>
那么我的路由器和控制器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铬扩展到Post)但是当我使用angularjs视图时,我得到了这个错误:
POST http:// localhost:3000 / api / users / login 400(Bad Request)
请帮我解决,我想我错过了什么。 先谢谢你。
我想你是发送你的loginfunction,如下面的行:
$http.post('/api/users/login', $scope.login)
您可能想要在您的loginfunction中传递一个参数,并将其发送到服务器,如下所示:
$scope.login = function(loginData) { $http.post('/api/users/login', loginData).success(function (response)
更新
您正在将您的表单值分配给$ scope.login。 如果你要为它创build一个单独的variables,例如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(); }); }; }]);