超薄的开机自检呼叫无法从 Ionic 应用程序工作

Slim POST calls do not work from Ionic app

本文关键字:Ionic 应用程序 工作 开机自检 呼叫      更新时间:2023-09-26

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

ionic serve --lab

这很完美,但是当我转到应用程序设备调用API时报告我404,我留下了我的应用程序的详细信息:

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/配置文件

$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();
            }
        });
});

如果要试用该服务,请使用以下 URL:http://skulapp.com/nuevo/service/get_profile/profile/eudes/5338eb5355db63e418c6b707ab00ccdf

嗨,我的

问题的答案是添加白名单插件并在我的 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-whitelist 和 https://github.com/phonegap/phonegap-start/blob/master/www/config.xml(感谢尼科尔斯)

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