Search code examples
javascripthtmlcorsp5.js

CORS request denied when running HTML/JS file


I have an HTML/CSS/JS program that uses p5.min.js and works perfectly fine. However, whenever I use it to load an image / JSON / font file, it gives me the following error:

Access to XMLHttpRequest at 'file:///C:/Users/ ... /Fonts/RubikMonoOne-Regular.ttf' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome-untrusted, https, edge.

The section which throws the error within my code:

let font;
function preload() {
    font = loadFont("./Fonts/RubikMonoOne-Regular.ttf"); // loadFont stems from p5.js
}

I am not sure what is causing the error as I haven't tried to do anything fancy, just run the p5js loadFont command. I am not sure why it is even a cross-origin request, given that they don't work even when in the same directory. I am simply running the file on my desktop, not using a web or localhost server.

I've found several answers online, but none of them work for me. All of them seem to be for deployed servers or localhost. For reference, I am using Microsoft Edge, but Chrome doesn't work either.

I found an answer which suggested running MS Edge / Chrome via cmd with:

–-allow-file-access-from-files --disable-web-security --user-data-dir --disable-features=CrossSiteDocumentBlockingIfIsolating` but in both cases that just tried to open an invalid link `xn---allow-file-access-from-files-k71r/

If I can, I would like to avoid running a localhost server as that has also given me trouble. However, I am hoping to upload the file to fxhash, so any solution would need to be universal.

I'm not sure why it has gotten to be this complicated, I thought it would be a super easy process given it's only double-clicking on an HTML file to run it without servers, etc.


Solution

  • I am guesting that you are using the html file by directly openning it?!
    You need to run your html file inside a local server.

    Here are some helpful links to get you started :
    https://timnwells.medium.com/quick-and-easy-http-servers-for-local-development-7a7df5ac25ff
    https://www.npmjs.com/package/http-server
    https://codingshower.com/quick-local-web-server/