Alex Michailidis
Alex Michailidis

Reputation: 4143

Include cross origin html template

I am trying to include an html template with angular like this

<div ng-include="http://SOME_OTHER_DOMAIN/template.html"></div>

As shown, the template is in another domain, to be more specific in an s3 bucket. I have full control in this bucket and I have already applied cors configuration like this.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
   <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

As expected the template loads correctly and by inspecting the network traffic chrome show this response headers:

access-control-allow-methods:GET
access-control-allow-origin:*
access-control-max-age:3000
content-encoding:gzip
content-type:text/html
........

Now the strange thing is that without any modification or change, the template stops loading and the browser complains that there is no access control allow policy on the request. And in fact when I inspect the network once again the CORS headers are missing. This happens randomly, and even checking the website from chrome and firefox at the same time, one browser will find the CORS as expected and the other will not.

I have read about the the browser's Same Origin Policy and Cross-Origin Resource Sharing (CORS) policy, but I found this behavior really strange.

I want your suggestions on this, is this even a browser problem, cache related, S3 bug or something else?

I have found some solutions involving a proxy server to just giving CORS to request that don't have, but keeping a server just for this is a little awkard, let alone that s3 has already implemented CORS by default.

Upvotes: 1

Views: 648

Answers (1)

Ryan
Ryan

Reputation: 6517

Given the intermittent nature of this failure, my guess would be that the browser has cached the html file you're trying to load, and this cached version was not loaded with CORS.

So basically - do you load the file earlier without going through CORS? Then a second request that is cross-domain would require it, but never even leave the browser because the resource has already been cached.

Are you loading the template file directly in your browser by typing in the url to it (not a cross-domain request, because you're accessing it directly out of its bucket)?

One possible fix for this is to add a cache-busting pattern to the url to the template, which would mean the browser cannot cache it e.g. append ?nocache to the end of the template url.

See this answer: https://stackoverflow.com/a/14238351/808532

edit: also, maybe now angular works without this, but shouldn't the url string be single-quoted inside your ng-include attribute?

e.g. ng-include="'http://SOME_OTHER_DOMAIN/template.html'"

Upvotes: 2

Related Questions