Search code examples
javascriptnode.jscorsinteractjs

Avoiding CORS issues on web app importing JavaScript modules from other domains


I am building a web application using NodeJS splitting the application into a back-end to handle database queries with MongoDB and a front end via a node based webserver that uses interactjs with JavaScript compiled from TypeScript. Currently, I have it running on LocalHost.

For my front end, leaning on my desktop application development skills, I originally built an application modularly out of several JS modules in a serverless, on the local machine not even using local host, way. It constructs flowcharts drag and drop style implemented using typescript compiled to JS. I have now moved it into node. Most things seem to be working, but in one of my modules I am importing interact.js to handle my drag and drop.

import interact from 'https://cdn.jsdelivr.net/npm/@interactjs/interactjs/index.js'

However, this seems to be causing CORS errors to be reported by my browser Firefox. I have done quite a bit of reading and understand what Cross Origin Resource Sharing is, and why problems occur. However, I have yet to find a good source of information that helps me overcome my problem. A lot of the information seems to either describe what a CORS error is without offering a solution or provides examples mime types,or fetch commands which are not relevant to this (as far as I know).

If you are running a webapp that is at http://localhost:5000/myApp. How then can my code import external JavaScript modules without triggering the CORS errors?

What I am seeing many times over in the console of Firefox's is three likely related errors:

Loading module from “https://cdn.jsdelivr.net/npm/@interactjs/actions/drag/plugin” was blocked because of a disallowed MIME type (“text/plain”).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://cdn.jsdelivr.net/npm/@interactjs/actions/drag/plugin. (Reason: CORS request did not succeed). Status code: (null).

Module source URI is not allowed in this document: “https://cdn.jsdelivr.net/npm/@interactjs/actions/drag/plugin”.

I'm posting here out of desperation, as I have spent all day going around in circles and have not been able to find anything related to my problem on StackOverflow or elsewhere.


Solution

  • The @interactjs/interactjs module isn't meant to be used over a CDN — you probably want interactjs (without the leading @), because it looks like the namespaced versions are really meant for internal and build-time use. If you just need drag, you can get that from their CDN: import 'https://cdn.interactjs.io/v1.9.20/actions/drag/index.js'.