AJAX request failed to use the file:/// protocol at source. How to resolve?

Asked

Viewed 68 times

2

I am making a very simple program where I need to read a . txt file with Javascript. I am not using any IDE, I just created . html files, . js and . txt in a folder.

To simplify the question, I created in a folder the following HTML code:

<head>
    <meta charset="utf-8">
    <title>Titulo</title>
</head>
<body>
    <script type="text/javascript" src="lerTXT.js"></script>
</body>

I found online a code (8 years ago) that made sense. So I created lerTXT.js thus:

var rf = new XMLHttpRequest();
rf.open("GET", "exDados.txt", false); // recebo warning por deixar síncrono
rf.onreadystatechange = function(){
    if(rf.readyState === 4){
        if(rf.status === 200 || rf.status == 0){
            var texto = rf.responseText;
            alert(texto);
        }
    }
}
rf.send(null);

When I run HTML in Firefox, it returns an error like:

Blocked cross-origin request: Same Origin Policy (Same Origin Policy) prevents reading the remote resource in file://C:/Users/Arthur/Desktop/project/exDados.txt. (Reason: CORS request is not HTTP).

Or:

Fetch API cannot load file://C:/Users/Arthur/Desktop/project/exDados.txt. URL Scheme must be "http" or "https" for CORS request.

I understood that this is to restrict access to addresses other than the domain of the application. But in this case it’s just a file in the same folder. I didn’t put it on any server or anything like that.

I found that in the past Firefox and other browsers understood file:/// like same domain, but now no more. Is there anything I can add to the code so it ignores the cross-orign lock? Or maybe a new way to upload files?

I know you can use the tag <input type="file"> to receive files, but wanted Javascript to automatically load . txt without requiring the user to load it.

  • maybe you should try something more modern :) you can use File API, see here: https://w3c.github.io/FileAPI/

  • Yes, I took a look at this API and what I found was its relationship to the tag <input type="file">, where the user manually loads the file. It has how to use this API but loading the file automatically and without cross-orign blocking?

  • @Arthurjc There is more than one problem with your code, first the FILE protocol does not work with Xmlhttprequest, as I mentioned in https://answall.com/a/239475/3635, second, you used the third parameter as FALSE in . (open) and then used onreadystatechange, which makes no sense, because the false will indicate to be synchronous and not asynchronous, so this would not be "Ajax", as I explained in AJAX is not a programming language. So what is?

  • 1

    Third, if the goal is to read files from the client’s machine, you need to use a <input type="file"> with the native JS File api, as I provided for example in: How to read binary file content in Javascript. If that’s not the case and you’re trying to read a file within the project, then the problem is that you’re running the HTML page on the file protocol (I’m not talking about the ajax part, I’m talking about the whole page), some details on https://answall.com/a/62797/3635

  • That’s right Guilherme, was running on FILE protocol. With his explanation and Luiz Felipe’s was much clearer. I will now use the Web Server for Chrome extension, so I won’t need to use the tag <input type="file">. Thank you!

  • @Arthurjc actually input=file is for something else, as I explained in the comments, or the problem is to read a local file, which will solve in one way, or the problem is to read a file of the "application", which in this case dispenses the input, the treatment is everything in the application environment, because in the question it was not clear what the purpose, read user files or file within the application ;) ... Do not forget the detail of synchronous and asynchronous, which is another problem in your code, which although it still works should be adjusted

Show 1 more comment

1 answer

0


You are trying to make an XHR request (or Fetch, in terms modern). Other people may understand how to request AJAX.

In summary, CORS is:

CORS (Cross-Origin Resource Sharing) is a system consisting of transmitting HTTP headers, which determines whether browsers will block Javascript code from accessing responses from requests between sources.

[Source]

That is, it is a set of security policies implemented by browsers that determine whether Javascript code can access response requests between sources (take this as the above mentioned AJAX requests). About CORS itself, you can consult more on What is the meaning of CORS?

Among the policies (see documentation - here and here) CORS, you can cite the one that prohibits AJAX requests to be executed when the source does not use the protocol http: or https:. And it is this policy that causes the problem detailed in the question.

Note that you did not upload a server to perform the request. You are accessing the HTML file directly from the browser using the protocol file:. Naturally, therefore, the XHR request will be blocked by the browser’s CORS policy, since it is neither HTTP nor HTTPS.

You can consult the origin protocol with this code:

console.log(location.protocol);

The documentation gives more details about this specific error: Reason: CORS request not HTTP.

Solution

The solution is simple: you must execute the request so that the source is in protocol http: or https:. For this, in a development environment, the most common solution is to use a local development server.

If you are immersed in the Node.js ecosystem, you can use the CLI serve. Another option is to use a text editor extension. In Vscode, the most common for this purpose is Live Server extension.

  • Got it. I appreciate the very detailed explanation! I was afraid it would be something like this... I’m not using any IDE, I did everything on Notepad++ anyway. I liked your suggestion about extension to text editor. I’ll look for a local server then. I found for Atom (Atom live server), but not for Notepad++. Do you know any?

  • 1

    For Nodepad++ I don’t know. : / If the answer solved your problem, you can accept it by clicking the check icon in the upper left corner. :)

  • 1

    I found the extension: "Web Server for Chrome". It worked super well! I’m going to adopt it from now on.

  • Reply Accept! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.