问题
I have developed an app using AngularJS.
It is live at the following url but it isn't working because of CORS issue on loading templates: http://www.ebust.it/app/#/lines/list
The app works fine on the url without "www": http://ebust.it/app/#/lines/list
The error that I get from js console:
XMLHttpRequest cannot load http://ebust.it/themes/frontend/spa/app/views/lines.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.ebust.it' is therefore not allowed access.
I also tried to force the template as absolute URL. Have you ever experiences something similar? I can't understand why Angular is using the wrong domain to perform the AJAX request for the template URL.
回答1:
The $http
Ajax requests become cross-origin when requests for the scripts are redirected:
<script src="/themes/frontend/spa/app/scripts/controllers/line.js"></script>
curl -v http://www.ebust.it/themes/frontend/spa/app/scripts/services/line.js
...
< HTTP/1.1 301 Moved Permanently
...
< Location: http://ebust.it/themes/frontend/spa/app/scripts/services/line.js
...
Each script is tied to is the origin that serves it, http://ebust.it/
, rather than that of the document, http://www.ebust.it/
.
To resolve this, you could:
Serve the scripts from both origins rather than redirecting.
Specify the hostname that serves the scripts in the Ajax URLs:
return $http({ // ... url: '//ebust.it/line/georeverse' });
Adjust the origin with document.domain.
document.domain = 'ebust.it';
url: '//' + document.domain + '/line/georeverse'
Or configure CORS to allow the requests between the 2 origins.
回答2:
Have you tried relative URLs instead of absolute ones? What are you using for routing? ui-router? Ideally if you're using ngRouter or ui-router, if you give relative paths, this will not cause CORS issues. CORS comes into picture only if you give absolute (and incorrect i.e. belonging to a different domain) URL
回答3:
You can use window.location.hostname
or the Angular way $location.host()
to get the appropriate "www.ebust.it" or "ebust.it" and load the template by concatenating the path to the host.
来源:https://stackoverflow.com/questions/24616126/angularjs-template-url-loading-throws-cors-error