超薄POST调用不适用于Ionic应用程序

时间:2016-01-21 15:42:41

标签: javascript php angularjs ionic-framework slim

我有一个应用程序可以通过POST调用并获取REST API,APP正在使用Ionic进行开发,并在使用以下命令模拟应用程序时使用:

ionic serve --lab

这很有效,但是当我去app设备调用API报告给我404时,我会留下我的APP的详细信息:

app.constants.js:

.constant('REST_SERVICE', {
    url: 'http://skulapp.com/nuevo/service',
    services: {
        profile:              '/get_profile/profile'/*,
        contacto:           '/contactos/',
        contactosExport:     '/contactosExport/',
        campanna:           '/campannas/',
        sync_contactos:     '/sync_contactos/',
        sync_campannas:     '/sync_campannas/'*/
    }
})

app.controller.js:此功能使用该服务:_Auth_Service

$scope.login = function(_credentials){
        if(_credentials != null){
            $ionicLoading.show({
                template: '<ion-spinner icon="lines" class="spinner-calm"></ion-spinner>'
            });
            _Auth_Service.verify({user: _credentials.user, pass: hex_md5(_credentials.pass)}).then(function(profile){
                $state.go('main.dashboard', {}, {reload: true});
                //console.log(profile);
                $scope.setCurrentUsername(profile);
                $ionicLoading.hide();
            }, function(err) {
                var alertPopup = $ionicPopup.alert({
                    title: 'Usuario no Valido',
                    template: 'Por favor revise su usuario y contraseña'
                });
                $ionicLoading.hide();
            });
        } else
            var alertPopup = $ionicPopup.alert({
                title: 'Inicio Cancelado',
                template: 'Ingrese su usuario y contraseña'
            });
    }

app.services.js:服务_Auth_Service,使用服务_API

    .service('_Auth_Service', function($q, $http, _API, USER_ROLES){

        var authService = {};
        var LOCAL_TOKEN_KEY = 'LocalAppToken';
        var username = '';
        var isAuthenticated = false;
        var role = '';
        var authToken;

        authService.verify = function(credentials){
            return _API.get('profile', credentials).then(function(res){
                console.log(res);
                //console.log(res.data['_id_PER']);
                storeUserCredentials(credentials.user + '.yourServerToken');
                storeUserRol(res.data[0].Rol_USU)
                return res.data[0];
            });
        };

        return authService;

function loadUserCredentials() {
        var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
        if (token) {
            useCredentials(token);
        }
    }

        function storeUserCredentials(token) {
            window.localStorage.setItem(LOCAL_TOKEN_KEY, token);
            useCredentials(token);
        }

        function useCredentials(token) {
            username = token.split('.')[0];
            isAuthenticated = true;
            authToken = token;
            console.log('usa credenciales: ' + token + ' isAuthenticated: ' + isAuthenticated);
            // Set the token as header for your requests!
            $http.defaults.headers.common['X-Auth-Token'] = token;
        }

        function storeUserRol(rol) {
            //console.log('Rol: '+rol);
            role = rol;
        }

        loadUserCredentials();
        return {
            login: login,
            logout: logout,
            isAuthorized: isAuthorized,
            isAuthenticated: function() {
                return isAuthenticated;
            },
            username: function() {
                return username;
            },
            role: function() {
                return role;
            }
        };
    })

.service('_API', function($http, REST_SERVICE){

    this.get = function(_service, _data){
        var _url = REST_SERVICE.url+REST_SERVICE.services[_service];
        angular.forEach(_data, function(val, key){
            _url += '/' + val;
        });
        for (var i = 0; i < _data.length; i++){
            console.log(_data[i]);
            _url += '/' + _data[i];
        }
        return $http.get(_url);
    }

    this.post = function(_service, _data){
        var _url = REST_SERVICE.url+REST_SERVICE.services[_service];
        //console.log(_data);
        return $http.post(_url, _data);
    }

})

REST API: get_profile / profile

$app->group('/get_profile', function() use($app){


        $app->post('/profile', function() use($app){
            try{
                //$app->response()->header("Content-Type", "application/json");

                $_datos = $app->request();
                //$objDatos = json_decode(file_get_contents("php://input"));

                $body = $_datos->getBody();
                $objDatos = json_decode($body);

                $_jobs = new Jobs();

                //$_sql = 'SELECT u._id_PER, p._id_IMA, p.Nombre_PER, p.Apellidos_PER, p.Identificacion_PER, p.Telefono_PER, p.Celular_PER, p.Correo_PER, p.Sexo_PER, p.Direccion_PER, t.Nombre_TPO Tipo_PER, u.Nombre_USU, u.Clave_USU, u.SO_Plataforma_USU, u.Rol_USU, p.Creado_PER Actualizado_PER FROM Usuarios u INNER JOIN Personas p ON p._id = u._id_PER INNER JOIN Tipos t ON t._id = p._id_TPP WHERE (Nombre_USU = "'.$objDatos->user.'") AND (Clave_USU = "'.$objDatos->pass.'")';

                $_sql = 'SELECT u._id_PER, p._id_IMA, p.Nombre_PER, p.Apellidos_PER, p.Identificacion_PER, p.Telefono_PER, p.Celular_PER, p.Correo_PER, p.Sexo_PER, p.Direccion_PER, t.Nombre_TPO Tipo_PER, u.Nombre_USU, u.Clave_USU, u.SO_Plataforma_USU, u.Rol_USU, p.Creado_PER Actualizado_PER FROM Usuarios u INNER JOIN Personas p ON p._id = u._id_PER INNER JOIN Tipos t ON t._id = p._id_TPP WHERE (Nombre_USU = "'.$objDatos->{'user'}.'") AND (Clave_USU = "'.$objDatos->{'pass'}.'")';

                //$_sql = 'SELECT u._id_PER, p._id_IMA, p.Nombre_PER, p.Apellidos_PER, p.Identificacion_PER, p.Telefono_PER, p.Celular_PER, p.Correo_PER, p.Sexo_PER, p.Direccion_PER, t.Nombre_TPO Tipo_PER, u.Nombre_USU, u.Clave_USU, u.SO_Plataforma_USU, u.Rol_USU, p.Creado_PER Actualizado_PER FROM Usuarios u INNER JOIN Personas p ON p._id = u._id_PER INNER JOIN Tipos t ON t._id = p._id_TPP WHERE (Nombre_USU = "'.$_datos->post('user').'") AND (Clave_USU = "'.$_datos->post('pass').'")';

                $app->response->headers->set("Content-type", "application/json");
                $app->response->setHeader('Access-Control-Allow-Origin', '*');
                $app->response->status(200);
                $app->response->body(json_encode($_jobs->get_execute($_sql)));

            }catch(PDOException $e){
                $app->response->status(500);
                echo "Error: Descargando los datos " . $e->getMessage();
            }
        });

        $app->get('/profile/:user/:pass', function($_Nombre_USU = '', $_Clave_USU = '') use($app) {
            try{
                $_jobs = new Jobs();

                $_sql = 'SELECT u._id_PER, p._id_IMA, p.Nombre_PER, p.Apellidos_PER, p.Identificacion_PER, p.Telefono_PER, p.Celular_PER, p.Correo_PER, p.Sexo_PER, p.Direccion_PER, t.Nombre_TPO Tipo_PER, u.Nombre_USU, u.Clave_USU, u.SO_Plataforma_USU, u.Rol_USU, p.Creado_PER Actualizado_PER FROM Usuarios u INNER JOIN Personas p ON p._id = u._id_PER INNER JOIN Tipos t ON t._id = p._id_TPP ';

                $_where = 'WHERE ';

                if($_Nombre_USU != '') {
                    if($_Clave_USU != '') 
                        ($_where == 'WHERE ') ? $_sql .= $_where.'(Nombre_USU = "'.$_Nombre_USU.'") AND (Clave_USU = "'.$_Clave_USU.'")' : $_sql .= $_where.' AND (Nombre_USU = "'.$_Nombre_USU.'") AND (Clave_USU = "'.$_Clave_USU.'")';
                }

                $app->response->headers->set("Content-type", "application/json");
                //$app->response->setHeader('Access-Control-Allow-Origin', '*');
                $app->response->status(200);
                $app->response->body(json_encode($_jobs->get_execute($_sql)));
            }catch(PDOException $e){
                $app->response->status(500);
                echo "Error: Descargando los datos " . $e->getMessage();
            }
        });
});

如果您想尝试该服务,请使用以下网址:http://skulapp.com/nuevo/service/get_profile/profile/eudes/5338eb5355db63e418c6b707ab00ccdf

1 个答案:

答案 0 :(得分:0)

我的问题的答案是添加白名单插件并在我的config.xml文件中添加以下配置:

<allow-navigation href="http://skulapp.com/*" />
  <access origin="http://skulapp.com" />
  <access origin="*"/>
  <allow-intent href="http://*/*" />
  <allow-intent href="https://*/*" />
  <allow-intent href="tel:*" />
  <allow-intent href="sms:*" />
  <allow-intent href="mailto:*" />
  <allow-intent href="geo:*" />
  <platform name="android">
    <allow-intent href="market:*" />
  </platform>
  <platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
  </platform>

https://github.com/apache/cordova-plugin-whitelisthttps://github.com/phonegap/phonegap-start/blob/master/www/config.xml(感谢Nicholls)

我需要访问域名,但是我的白名单上没有添加,所以这个插件我允许操作这些配置细节,添加域名并且它运行良好。