0

Im having trouble making REST API calls in my ionic app to my server. It shows the following error.

ionic.bundle.js:25005 OPTIONS https://website.com/api/ionic_test 406 (Not Acceptable)

XMLHttpRequest cannot load https://website.com/api/ionic_test. Response for preflight has invalid HTTP status code 406

API call code.

$http.post(API_ENDPOINT.url + '/ionic_test', user).then(function(result) {
                    if (result.data.status) {
                        storeUserCredentials(result.data.token);
                        resolve(result.data.msg);
                    } else {
                        reject(result.data.msg);
                    }
                });

ionic.config.json

{
  "name": "adminPanel",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://website.com/api"
    }
  ]
}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Salman
  • 389
  • 4
  • 22
  • look up CORS, there are quite a few questions and answers to this already. – Claies Jan 31 '17 at 19:35
  • in fact, 2,817 questions with `No 'Access-Control-Allow-Origin' header is present ` "http://stackoverflow.com/search?q=No+%27Access-Control-Allow-Origin%27+header+is+present" – Claies Jan 31 '17 at 19:36
  • @Claies I have gone through many similar questions. enabling CORS gives me this error. question has been edited – Salman Jan 31 '17 at 19:44
  • this seems like a server issue, not an ionic issue... what kind of server is this? what do the routes look like? also, the error is showing `https://`; does it still give the same error with `http://`? – Claies Jan 31 '17 at 19:50
  • @Claies When I take the url in browser im getting the response. But not in the ionic app. Do you want the complete api url? – Salman Jan 31 '17 at 19:54

2 Answers2

1

The problem is with your server. In the comments you said the API works in browser, but not in your app. That's because your browser doesn't send an OPTIONS "preflight" request, which Ionic does.

You need to either disable the preflight request, or configure your server to handle it properly.

Community
  • 1
  • 1
Schlaus
  • 18,144
  • 10
  • 36
  • 64
0

Use these in your app config to resolve the preflight issue

$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};

Eg.

angular.module('yourApp', [])

.config(function ($stateProvider, $httpProvider, $urlRouterProvider) {

    //To solve Response for preflight has invalid HTTP 
    $httpProvider.defaults.headers.common = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};


    //--------------------------------------

    // your routes here
});
coder
  • 8,346
  • 16
  • 39
  • 53