0

I would like to understand why the AngularJS $http service doesn't work and the fetch API works.

Below is the AngularJS code:

const $http = angular.element(document.body).injector().get('$http')
$http({
  method: 'GET',
  url: 'http://192.168.1.126:8080/saiku/rest/saiku/admin/datasources/',
  headers: {
    'Authorization': 'Basic YWRtaW46YWRtaW4='
  }
})

This gives me this error:

angular.js:12845 OPTIONS http://192.168.1.126:8080/saiku/rest/saiku/admin/datasources/ 403 () Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access. The response had HTTP status code 403.

The weird part is that this:

fetch('http://192.168.1.126:8080/saiku/rest/saiku/admin/datasources/', {
    method: 'GET',
    headers: {
         'Authorization': 'Basic YWRtaW46YWRtaW4='
    }
}).then((r) => r.json()).then(console.log)

Gives me the correct response

I know this could be a CORS error, but i've added the CORS filter on my tomcat so everything should work (and fetch works). Is this a bug in fetch or $http?

1 Answer 1

2

While i was writing this question i found the answer:

On my AngularJS app, there was a config file that was setting this:

$httpProvider.defaults.headers.get['If-Modified-Since'] = '0';

And this (along with other headers), makes the request a preflighted one, as peer the CORS documentation:

[...] Apart from the headers set automatically by the user agent (for example, Connection, User-Agent, or any of the other header with a name defined in the Fetch spec as a “forbidden header name”), the request includes any headers other than those which the Fetch spec defines as being a “CORS-safelisted request-header”, which are the following:

  • Accept Accept-Language
  • Content-Language
  • Content-Type (but note the additional requirements below)
  • Last-Event-ID
  • DPR
  • Save-Data
  • Viewport-Width
  • Width

So the fetch API worked because it wasn't setting that (If-Modified-Since) header, and the $http service was.

Sign up to request clarification or add additional context in comments.

2 Comments

Im facing the same issue. Did you change the config file? Or do I have to use fetch() instead of $http?
@Ahmet sorry, I don't recall my solution, but I'm pretty sure that I was just curious about it, so I didn't fixed. You probably will need to either remove the header or configure CORs to accept another origin on your server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.