简体   繁体   中英

Local xml blocked by cors policy

I'm trying to read an XML file using JQuery... Or at the very least, I'm trying to access it. I have a file system made like this :

-> Main directory
    -> html
        -> home.html
    -> js
        -> jquery.js
        -> XMLReader.js (made it myself)
    -> XML
        -> test.xml

XMLReader.js is made like this :

'use strict'
$(document).ready(function()
{
    $.ajax( 
    {
        type: "GET",
        url: "../xml/test.xml",
        //async: false,
        dataType: "xml",
        success: function(xml)
        {
            console.log("ayy");
        }
    });
});

When I try to reach my XML file located in my xml folder, my request keeps getting blocked by CORS policy (when I am trying to access a LOCAL file !). On the other hand, if I put all the files in the same directory (and change the links of course), it works.

Basically, CORS policy is preventing me from organising my local web application.

Is there a way to solve this ? CORS Policy shouldn't be blocking me for trying to read a local file, right ?

Different browsers implement Same Origin Policy restrictions for files loaded from the file system in different ways.

Some:

  • Block access to all local files
  • Block access to all local files except those in the same directory or a subdirectory of the HTML file

CORS Policy shouldn't be blocking me for trying to read a local file.

Yes, it should. This is an important security feature.

You would not want someone sending you an HTML file as an attachment in an email, double-clicking it to open it, and then JavaScript embedded in it reading files from your hard disk and sending them to the person who sent the email.

Is there a way to solve this?

If you want to access local files, then either:

  • make your local files available over HTTP. You can run an HTTP server that listens only on the loopback network interface if you don't want to allow access from other computers.
  • use a browser which implements the weaker of the two security policies I described and rearrange your file system as you have already discovered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM