Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
244 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...