systemjs: Loading external resource (CORS) error

Why when I try to load module (using System.import) from external source I’ve got an error:

XMLHttpRequest cannot load ... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ...  is therefore not allowed access. 

But this resource can be loaded with <script> tag or jquery.getScript. I’m I doing something wrong? Can this be handled?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 32 (8 by maintainers)

Most upvoted comments

I think I’ve found a way to bypass cors altogether.

  1. Make surefetch loader is not used (i.e. script loader is always used)
  2. Simply add this snippets before loading modules:
var createScript = System.constructor.prototype.createScript;
System.constructor.prototype.createScript = function (url) {
  return Promise.resolve(createScript.call(this, url))
    .then(function (script) {
      script.crossOrigin = undefined;
      return script;
    });
};

Why it works

The culprit is the “crossorigin” attribute, more detail: https://stackoverflow.com/a/41069421

Normally, <script> tags don’t send “Origin” header when requesting script content and thus bypass CORS completely.

However, by adding “crossorigin” - even with “anonymous”, will lead to the browser sending the “Origin” header for <script> tags, and thus making them subject to CORS restrictions.

These lines

https://github.com/systemjs/systemjs/blob/main/src/features/script-load.js#L23-L24

will cause crossOrigin to be almost always added - (unless .indexOf() returns 0 which means script url begins with location.origin, i.e. your app domain is equal to your cdn domain)

By adding the above plugin, we always remove the “crossOrigin” attribute, and CORS is no more.