无法登录&得到以下错误:" TypeError:无法读取属性'代码'未定义"

时间:2016-02-16 12:45:09

标签: php mysql rest ionic-framework

我正在尝试使用php mysql作为后端并使用RESTful Web服务登录我的离子应用程序...运行我的项目后我收到此错误:" TypeError:无法读取属性'代码&# 39;未定义"在services.js 我的代码怎么了?

我的控制器是:

.controller('LoginCtrl', function ($scope, $state, LoginService) {
 $scope.login = function () {
    var obj={};
    obj.username=$scope.uname;
    obj.password=$scope.pswd;
    LoginService.loginUser(obj)
    .then(function (data) {
        $state.go("tab.dash");          //log in successfull
    }, function (data) {
        //log in failed
    });
 }
};

我的服务是:

.service('LoginService', function ($q, $http) {
 return {
    loginUser: function (loginData) {
        var deferred = $q.defer(),
            promise = deferred.promise;

        $http({
            url: 'http://localhost/login.php',
            method: "POST",
            data: loginData,
            headers: {'Content-Type': 'application/json'}
        })
            .then(function (response) {
                if (response.data.error.code === "000") {
                    console.log("User login successful: " + JSON.stringify(response.data));
                    deferred.resolve(response.data);
                } else {
                    console.log("User login failed: " + JSON.stringify(response.data.error));
                    deferred.reject(response.data);
                }
            }, function (error) {
                console.log("Server error on Login " + JSON.stringify(error));
                deferred.reject(error);
            });

        promise.success = function (fn) {
            promise.then(fn);
            return promise;
        };
        promise.error = function (fn) {
            promise.then(null, fn);
            return promise;
        };
        return promise;
    }
  };
 });

我的HTML代码是:

<ion-view view-title="Login">
<ion-content class="padding" ng-controller="LoginCtrl">
  <div class="list list-inset">
<ion-list> 

    <label class="item item-input item-floating-label">
        <span class="input-label">Username</span>
        <input type="text" placeholder="Username" ng-model="uname">
    </label>

    <label class="item item-input item-floating-label">
        <span class="input-label">Password</span>
                    <input type="password" placeholder="Password" ng-model="pswd">
    </label>

 </ion-list>

</div>   
  <br>
  <div class="col-sm-7">
    <button class="button ion-log-in button-block button-calm animated fadeInRight" ng-click="login()">Login</button>
</div>

我的PHP代码是:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, x-xsrf-token");

$postdata = file_get_contents("php://input");
$loginData = json_decode($postdata);
$email = $loginData->email;
$password = $loginData->password;

$userData = array('userID' => '', 'userName' => '', 'email' => '');

$conn = mysqli_connect("127.0.0.1", "root", "") or die('{"userData":'.json_encode($userData).', "error": {"code": "003", "message": "Login error! Code: 003"}}');
mysqli_select_db($conn, "userDB") or die('{"userData":'.json_encode($userData).', "error": {"code": "004", "message": "Login error! Code: 004"}}');

if(!empty($email) && !empty($password)){

//echo($email.'  '.$password);

$email = mysqli_escape_string($email);
$password = mysqli_escape_string(md5($password));

$results = mysqli_query("SELECT id,username, email, password FROM users WHERE email='".$email."' AND password='".$password."' LIMIT 1") or die('{"error":"Login error! Code: 003"}'); 
$match  = mysqli_num_rows($results);

$res = mysqli_fetch_assoc($results);

if($match > 0 ){        
    if ($res['active'] = 1) {
        // login success
        $userData['id'] = $res['id'];
        $userData['username'] = $res['username'];
        $userData['email'] = $res['email'];
        echo ('{"userData":'.json_encode($userData).',"error":{"code":"000","message":"Logged in as '.$userData['userName'].' '.'."}}');
    } else {                
        echo('{"userData":'.json_encode($userData).', "error":{"code":"001","message":"Your account has not been ativated. Please verify your account by clicking on the link in the activation email sent when you registered.\r\n If you did not receive an email, click on the Resend Activation Email link and make sure the email is not being blocked by your spam filter."}}');
    }
}else{
    // login failed
    echo ('{"userData":'.json_encode($userData).', "error": {"code": "002","message": "The email or password you entered is incorrect."}}');            
}
} else {
// something failed with submitting data, should never get here!
echo('{"userData":'.json_encode($userData).', "error": {"code":"005", "message": "Login error! Code: 005"}}');


}
    ?>

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您正在使用XMLHttpRequest到与您的网页不同的域名。因此浏览器会阻止它,因为出于安全原因,它通常允许同一来源的请求。当您想要执行跨域请求时,您需要做一些不同的事情。有关如何实现这一目标的教程是 Using CORS

当您使用邮递员时,他们不受此政策的限制。引自 Cross-Origin XMLHttpRequest

  

常规网页可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但它们受到相同原始策略的限制。扩展不是那么有限。扩展可以与其来源之外的远程服务器通信,只要它首先请求跨源权限。

来自this post

localhost的快速解决方案:安装this CORS plugin到chrome,允许您通过跨域请求。