Such a problem: I wrote userscript for the site. In it, I need to get the contents of the file " https: //site/answ.txt " from another site. But I can't do it at all. Here is one of the many attempts to do this.

var x = new XMLHttpRequest(); x.open("GET", "https://site/answ.txt", true); x.onload = function (x) { var x = this.responseText; alert(x); } x.send(); 

read this article http://learn.javascript.ru/xhr-crossdomain . But still nothing happened

  • If another site prohibits you from receiving information, then you can only do this through a proxy server. - Stepan Kasyanenko 1:16 pm
  • Well, I checked, through the browser I can get its contents, and in fiddler I created a request and everything was successful - Io Io
  • In the browser, of course, it will open separately, but in js it will not work if there are no necessary CORS headers at the end. How did it happen in your fiddler? I don’t know, is it not a file on the fiddler?) - Nikita Umnov 1:29 pm
  • No, on a free hosting - Io Io
  • In the chrome in the network tab (developer mode) such an inscription appears "Provisional headers are shown" - Io Io

1 answer 1

The solution was simple. When sending a request to another domain, for security reasons, the cors (security mechanism) blocks the response if it does not contain the Access-Control-Allow-Origin header: * (instead of a star, you can see our site from which the request was sent). This can be done by adding the following lines to the .htaccess file in the site root:

Header always set Access-Control-Allow-Origin "*" Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE" Header always set Access-Control-Allow-Headers: Authorization

In the second line we specify the allowed methods, in the first place * the site from which requests are allowed.

  • Simple in terms of what you did not have to change a lot of code? CORS is not so easy if you sort it all out. And I assume that if you indicated in the question that the site from which you want to receive the file belongs to you, then you would immediately be told about the lack of a title and what to add :) - Stranger in the Q