我遵循Jason Watmore的身份验证指南:http://www.jasonwatmore.com/post/2014/05/26/AngularJS-Basic-HTTP-Authentication-Example.aspx
我可以发送$http.post
并在我的console(response)
中取回成功。但由于某种原因,这并没有触发控制器重定向页面并让我登录。我觉得我没有返回系统期望的内容。
这是$ http.post
/* Dummy authentication for testing, uses $timeout to simulate api call
----------------------------------------------*/
//$timeout(function(){
// var response = { success: username === 'test' && password === 'test' };
// if(!response.success) {
// response.message = 'Username or password is incorrect';
// }
// callback(response);
// }, 1000);
/* Use this for real authentication
----------------------------------------------*/
$http.post('./Scripts/login.php', {
'Myusername': username,
'Mypassword': password
})
.success(function(response) {
console.log(response); //THIS RETURNS SUCCESS WHEN RIGHT
callback(response);
});
};
这是控制器
'use strict';
angular.module('Authentication')
.controller('LoginController',
['$scope', '$rootScope', '$location', 'AuthenticationService',
function ($scope, $rootScope, $location, AuthenticationService) {
// reset login status
AuthenticationService.ClearCredentials();
$scope.login = function () {
$scope.dataLoading = true;
AuthenticationService.Login($scope.username, $scope.password, function(response) {
if(response.success) {
AuthenticationService.SetCredentials($scope.username, $scope.password);
$location.path('/');
console.log("success");
} else {
$scope.error = 'Username or password is incorrect';
$scope.dataLoading = false;
console.log("error");
}
});
};
}]);
这是我的PHP
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$data = json_decode( file_get_contents('php://input') );
$username = $data->Myusername;
$userpassword = $data->Mypassword;
if (isset($data->Myusername)) {
if (isset($data->Mypassword)) {
$query=mysqli_query($conn,"SELECT * FROM UserTable WHERE username='$username' && password='$userpassword'");
$count=mysqli_num_rows($query);
$row=mysqli_fetch_array($query);
if ($count==1)
{
echo $response = 'success';
}
else
{
echo $response = 'error';
}
} else {
echo "password wrong";
}
} else {
echo "userID match";
}
mysqli_close($conn);
?>
答案 0 :(得分:0)
Austin你可能会遇到AngularJS的$ http POST的常见问题。例如,它的处理方式与jQuery不同。
您需要做一些事情,设置不同的内容类型,以及在发送数据之前序列化数据。
首先修改默认标题:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
然后使用JQuery的$ .param方法,在发送之前序列化你的数据。
$http.post(targetURL, $.param(yourObjectHere));
还有其他选项,例如默认使用$httpProvider.defaults.transformRequest
执行此操作。
$httpProvider.defaults.transformRequest = [function(data) {
return angular.isObject(data) && String(data) !== '[object File]' ? $.param(data) : data;
}];