• Hi, I’m having trouble with some javascript and CROSS policy.
    I need to import modules in javascript to extend some functionalities of Tone.js, a javascript library I want to use.
    I have one “import.js” file, with the following code:
    import {Context} from './node_modules/tone';
    The folder “node_modules” is inside my js folder with the import.js file too.
    I used “wp_enqueue_script” in functions.php to load the import.js file, and I used a filter to add the type="module"to the script tag.
    But, on loading, I got this error in console: “Access to script has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

    What have I to do here to correctly import it?

Viewing 2 replies - 1 through 2 (of 2 total)
  • A browser will emit a CORS policy error like you have seen when you are attempting to load a javascript file off a different hostname to the one being shown in your browser. For example, if you navigate to https://example.com your browser will emit a CORS error if you try to load a javascript file from https://another.example.net because the hostnames differ indicating they are different sites. This is a cross-site-scripting mitigation. To fix you need to either ensure that your javascript files are all loaded from the same hostname as the page being displayed or to ensure that the javascript files are sent from their origin server with a header indicating that your site is allowed to access them. The header in the latter case is Access-Control-Allow-Origin and must be set to the hostname of the page loading the javascript.

    Thread Starter ilfedevisio

    (@ilfedevisio)

    Yeah I know, but the problem is that all the files are in the same folder on the same local server. The error is showing this:
    http://mysite.local:10003/wp-content/themes/projectsite/js/node_modules/tone/ redirected from
    http://mysite.local/wp-content/themes/projectsite/js/node_modules/tone

    is this a problem because i’m working on local server?

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘WordPress Import Node-modules with javascript problem’ is closed to new replies.