brent
brent

Reputation: 502

angular $http.get / restangular call fails

I have an ionic app (uses angular js). I am trying to make a call to my localserver (node express) using the restangular api (have also tried using $http.get).

I set the base url as

RestangularProvider.setBaseUrl('https://localhost:3000');

I have an interceptor defined to add a custom header:

interceptors.serialNumber = function (element, operation, what, url, headers, query) {
  return {
    headers: angular.extend({
      'x-serialnumber': deviceStore.serialNumber
    }, headers)
  };
};

I have tried the following restangular call:

Restangular.one('Admin').get()
     .then(function (data) {
        console.log(data);
       });
     }, function (error) {
       console.log(error);
     });

and the following using a $http call:

$http({
        method: 'GET',
        url: 'https://localhost:3000/Admin',
        headers: {
          'Content-Type': 'application/json',
          'x-serialnumber': '000000000'   
        }
      }).then(function (data) {
        console.log(data);
      }, function (error) {
        console.log(error);
      });

I always get the error condition where data=null | status=-1 | statusText=""

I do not see ANY request on the server side. It goes to the fail case immediately.

If I remove the custom header, I see the requests on the server side and get a good response (i.e. 200).

On the server side I am using the cors module: var app = express(); app.use(cors());

Upvotes: 0

Views: 106

Answers (1)

brent
brent

Reputation: 502

Well what I needed to do was the following:

$http({
  method: 'GET',
  url: 'https://example.com/DUMMY'
}).then(function successCallback(response) {
  $http({
    method: 'GET',
    url: 'https://example.com',
    headers: {
      'x-serialnumber': deviceStore.serialNumber
    }
  }).then(function successCallback(response) {
    console.log('SUCCESS');
  }, function errorCallback(response) {
    console.log('FAILURE');
  });
}, function errorCallback(response) {
  console.log('FAILURE');
});

In essence, I needed to send a "preliminary" GET request with NO custom header. The GET request could be to anything on my node express server. After this "preliminary" GET request, I could perform the GET request with the custom header in it.

Specifically on the server side I see the following:

GET /DUMMY 200 10ms - 2b
OPTIONS / 204 1ms
GET / 200 13ms - 1.03kb

Without performing this "preliminary" get request, the OPTIONS request in my Ionic App would abort - status code = -1 - usually means the request was aborted and would never leave Ionic App side.

I still do not understand why I need this "preliminary" GET request, but this works for me.

Upvotes: 0

Related Questions