Search code examples
angularjsrestangular

I got an error when I execute getList with angular and restangular


Hi everybody I am developing an app with a backend made in Wordpress with a rest api.

But I can't parse the response, and I have no idea why, first I think that it was the kind of json response, thats why I implemet the setResponseInterceptor method.

The problem here is that I am not sure if the setResponseInterceptor, I add debug code and I dont see the logs in weiner.

I have the follow model with some global configuration:

// The contents of individual model .js files will be concatenated into dist/models.js

(function() {

// Protects views where angular is not loaded from errors
if ( typeof angular == 'undefined' ) {
    return;
};


var module = angular.module('Provedores_floresModel', ['restangular']);

module.factory('Provedores_floresRestangular', function(Restangular) {

  return Restangular.withConfig(function(RestangularConfigurer) {

    RestangularConfigurer.setBaseUrl('https://public-api.wordpress.com/rest/v1/sites/www.bride2be.com.mx/');
    RestangularConfigurer.setResponseInterceptor(function(response, operation, what, url){

        var newResponse;

        if (operation === "getList") {
            newResponse = response.posts;
        }

        return newResponse;
    });

  });

});


})();

and this controller:

var provedores_floresApp = angular.module('provedores_floresApp', ['Provedores_floresModel', 'hmTouchevents']);


// Index: http://localhost/views/provedores_flores/index.html

provedores_floresApp.controller('IndexCtrl', function ($scope, Provedores_floresRestangular) {

  // Helper function for opening new webviews
  $scope.open = function(id) {
    webView = new steroids.views.WebView("/views/provedores_flores/show.html?id="+id);
    steroids.layers.push(webView);
  };

  // Fetch all objects from the local JSON (see app/models/provedores_flores.js)
  $scope.provedores_floress = Provedores_floresRestangular.all('posts?type=ceremonia').getList().then(function() {
    alert("All ok");
  }, function(response) {
    alert(JSON.stringify(response));
  });
  // -- Native navigation
  steroids.view.navigationBar.show("Flores");

});

on the then codeblock I got the follow response:

{
    "data": "",
    "status": 0,
    "config": {
        "method": "GET",
        "headers": {},
        "url": "https://public-api.wordpress.com/rest/v1/sites/www.bride2be.com.mx/posts?type=ceremonia"
    }
}

Solution

  • The problem was CORS so I add the follow code to my .htaccess

    RewriteEngine On                  
    RewriteCond %{REQUEST_METHOD} OPTIONS 
    RewriteRule ^(.*)$ $1 [R=200,L]
    
    <ifModule mod_headers.c>
        Header always set Access-Control-Allow-Origin: "*"
        Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
        Header always set Access-Control-Allow-Headers "X-Requested-With"
    </ifModule>