如何为此角度登录代码连接数据库

时间:2016-10-26 06:35:07

标签: javascript php angularjs angularjs-scope

**我有登录代码。我硬编码用户名和密码。 现在我必须使用php连接数据库。我必须创建那个GET或POST方法。我需要创建此get或post方法服务文件或控制器文件。如何结合该文件的代码。

我正在使用php做后端文件。 **

service.js

b

controller.js

'use strict';


angular.module('Authentication')

.factory('AuthenticationService',
    ['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
    function (Base64, $http, $cookieStore, $rootScope, $timeout) {
        var service = {};

    service.Login = function (username, password, callback) {

        /* 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('/api/authenticate', { username: username, password: password })
        //    .success(function (response) {
        //        callback(response);
        //    });

    };

    service.SetCredentials = function (username, password) {
        var authdata = Base64.encode(username + ':' + password);

        $rootScope.globals = {
            currentUser: {
                username: username,
                authdata: authdata
            }
        };

        $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
        $cookieStore.put('globals', $rootScope.globals);
    };

    service.ClearCredentials = function () {
        $rootScope.globals = {};
        $cookieStore.remove('globals');
        $http.defaults.headers.common.Authorization = 'Basic ';
    };

    return service;
}])


.factory('Base64', function () {
    /* jshint ignore:start */


var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

return {
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;

        do {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
                keyStr.charAt(enc1) +
                keyStr.charAt(enc2) +
                keyStr.charAt(enc3) +
                keyStr.charAt(enc4);
            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";
        } while (i < input.length);

        return output;
    },

    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3 = "";
        var enc1, enc2, enc3, enc4 = "";
        var i = 0;

        // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
        var base64test = /[^A-Za-z0-9\+\/\=]/g;
        if (base64test.exec(input)) {
            window.alert("There were invalid base64 characters in the input text.\n" +
                "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
                "Expect errors in decoding.");
        }
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        do {
            enc1 = keyStr.indexOf(input.charAt(i++));
            enc2 = keyStr.indexOf(input.charAt(i++));
            enc3 = keyStr.indexOf(input.charAt(i++));
            enc4 = keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

            chr1 = chr2 = chr3 = "";
            enc1 = enc2 = enc3 = enc4 = "";

        } while (i < input.length);

        return output;
    }
};

/* jshint ignore:end */
});

1 个答案:

答案 0 :(得分:0)

用于本地数据库

1.在你的local.ie中使用 htdocs <创建一个名为 yourfolder 的文件夹中的Api.php,.htaccess,rest.in.php等php文件/ p>

2.现在你的services.js

声明您的主机如下

var hostname = "localhost:/yourfolder";

然后创建一个服务库来调用你的php代码,如下所示

var serviceBase = 'http://'+hostname+'/api.php';

现在在service.js中的login方法内部调用php方法,该方法执行后端进程的登录

 function Login(data) {
                $http.post(serviceBase+"?action=doLogin",data)
                    .success(function (response) {
                        callback(response, true);

                    })
                    .error(function(error){
                        callback(error, false);
                    })
            }

3.现在这将调用你的php文件并执行doLogin方法。所以你需要在你的php文件中配置你的数据库。所以它应该如下所示

<强> Api.php

<?php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');    
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 

    require_once("Rest.inc.php");

    class API extends REST {

        public $data = "";

        const DB_SERVER = "localhost";
        const DB_USER = ""; your DB username
        const DB_PASSWORD = ""; your DB password
        const DB = "";your DB name

        private $db = NULL;
        private $mysqli = NULL;
        public function __construct(){
            parent::__construct();              // Init parent contructor
            $this->dbConnect();                 // Initiate Database connection
        }

        /*
         *  Connect to Database
        */
        private function dbConnect(){
            $this->mysqli = new mysqli(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD, self::DB);
        }

        /*
         * Dynmically call the method based on the query string
         */
        public function processApi(){
            $func = strtolower(trim(str_replace("/","",$_REQUEST['action'])));

            if((int)method_exists($this,$func) > 0) {
                $this->$func();
                        } else
                $this->response('',404); // If the method not exist with in this class "Page not found".
        }
        /**
                 * if post data email and password is correct then,
                 * it will send the user object as return.
                 * else post data is wrong send the error report.
                 */

            private function Dologin(){
//wirte your php code here to send data to db 

            }


    }

    $api = new API;
    $api->processApi();

?>

<强> Rest.inc.php

<?php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');    
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 

    class REST {

        public $_allow = array();
        public $_content_type = "application/json";
        public $_request = array();

        private $_method = "";      
        private $_code = 200;

        public function __construct(){
            $this->inputs();
        }

        public function get_referer(){
            return $_SERVER['HTTP_REFERER'];
        }

        public function response($data,$status){

            $this->_code = ($status)?$status:200;
            $this->set_headers();
            echo $data;
            exit;
        }
        // For a list of http codes checkout http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
        private function get_status_message(){

            $status = array(
                                    200 => 'OK',
                                    201 => 'Created',  
                                    204 => 'No Content', 
                                    400 => 'validations',
                                    404 => 'Not Found',  
                                    406 => 'Not Acceptable');
                        error_log(($status[$this->_code])?$status[$this->_code]:$status[500]);
            return ($status[$this->_code])?$status[$this->_code]:$status[500];
        }

        public function get_request_method(){
                    return $_SERVER['REQUEST_METHOD'];
        }

        private function inputs(){
            switch($this->get_request_method()){
                case "POST":
                    $this->_request = $this->cleanInputs($_POST);
                    break;
                case "GET":
                case "DELETE":
                    $this->_request = $this->cleanInputs($_GET);
                    break;
                case "PUT":
                    parse_str(file_get_contents("php://input"),$this->_request);
                    $this->_request = $this->cleanInputs($this->_request);
                    break;
                default:
                    $this->response('',406);
                    break;
            }
        }       

        private function cleanInputs($data){
            $clean_input = array();
            if(is_array($data)){
                foreach($data as $k => $v){
                    $clean_input[$k] = $this->cleanInputs($v);
                }
            } else {
                if(get_magic_quotes_gpc()){
                    $data = trim(stripslashes($data));
                }
                $data = strip_tags($data);
                $clean_input = trim($data);
            }
            return $clean_input;
        }       

        private function set_headers(){
            header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
            header("Content-Type:".$this->_content_type);
        }
    }   
?>