2

My site provides a javascript file which the users can include in their site. This javascript file in-turn calls my applications endpoint and fetches some content that is then inputted into the users' div

This is the code for the JS

(function(){
    $(document).ready(function(){
        var test = $('#FooBar');
        var id = test.data('id');
        $.get('http://example.com/serve/'+id, function(data){
            test.html(data);
        });
    });
})();

But when a user references this JS file on their own site, they get the following error:

XMLHttpRequest cannot load http://example.com/serve/qeFz7TvGlg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.

This is the sample HTML I created to test

<!doctype html>
<html>
    <body>
        <div id="FooBar" data-id="qeFz7TvGlg"></div>
        <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
        <script src="http://example.com/scripts/myjsfile.js"></script>
    </body>
</html>
Anthony
  • 27,490
  • 32
  • 129
  • 238

2 Answers2

1

Your server needs to specify the Access-Control-Allow-Origin header (probably to *, which means "all"). This is called CORS.

To give a naive example, here's how you might do that in node.js:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

Edit

Since your server is in Grails, check out this question about how to enable CORS.

Community
  • 1
  • 1
Josh Beam
  • 17,535
  • 2
  • 32
  • 63
  • So, the webserver for my application (the one that is providing the JS file to customers) should add ` Access-Control-Allow-Origin ` to `*` when responding to the API call? – Anthony Feb 09 '16 at 01:58
  • Yep, something like that. You can configure the header however you want. You can specify only certain origins, or you can use all origins. I would suggest taking a look at the CORS link I provided in my answer. – Josh Beam Feb 09 '16 at 02:00
0

If you are running a Grails Server, look at this link. You should be able to open or create a web.xml file and copy the contents on the website into there.