0

HeIIo, I'm trying to create a small service, that would add some functionality to a webpage. The user inserts the following code on his website.

<script src="http://mywebsite.com/code.js"></script>

The purpose of this code is loading of an html element with the following request:

$.ajax({
    url: "http://mywebsite.com/element.html",
    method: 'GET',
    contentType: 'text/plain',
    xhrFields: {
        withCredentials: false
    },
    headers: {
    },
    success: function(data) {
        $('body').append(data);
    }
});

The problem is that I always get Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://mywebsite.com/element.html. This can be fixed by moving the resource to the same domain or enabling CORS.

I tried recommendations from this tutorial, but still getting the same errors. I also put the following row in .htaccess file: Header set Access-Control-Allow-Origin "*" - still no result. I would appreciate any recommendations on how else I can enable CORS.

  • `contentType: 'text/plain',` — Why do you have this? You are making a GET request. There is no request body to describe the content type of! – Quentin Aug 31 '14 at 12:42
  • 1
    Look at your browser's developer tools. Reload the page. Can you see your Ajax request in the Net tab? Is it formatted correctly? Does it get a response? Is the response correct? i.e. Can you see the **GET** request? Can you see the `Access-Control-Allow-Origin` header? – Quentin Aug 31 '14 at 12:43
  • no, I don't see Access-Control-Allow-Origin header, the rest of GET look normal – user3412802 Aug 31 '14 at 12:51
  • well, I mean what I'm sending is correct, but there is no response – user3412802 Aug 31 '14 at 12:56
  • `Access-Control-Allow-Origin` is a **response** header. You need to look for it on the response. – Quentin Aug 31 '14 at 13:00
  • `200` is the HTTP status code for `OK` and is part of the response. You can't have it unless there is a response. (If you didn't have one, you'd have a time out error) – Quentin Aug 31 '14 at 13:01
  • ok, see it, the response headers are: Connection: keep-alive, Content-Encoding: gzip Content-Type: text/html, Date: Sun, 31 Aug 2014 13:12:55 GMT, Last-Modified: Mon, 18 Aug 2014 19:22:38 GMT, Server: nginx/1.6.1, Transfer-Encoding: chunked. So there is no header that we are looking for. How can I add it? – user3412802 Aug 31 '14 at 13:17
  • well, I found a problem, I was using SET instead of ADD. Correct .htaccess: is Header add Access-Control-Allow-Origin "*" Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT" – user3412802 Aug 31 '14 at 13:39
  • I appreciate your help and patience, I really learned something from you, thanks – user3412802 Aug 31 '14 at 13:40

0 Answers0