Search code examples
javascriptcross-domainmarklogicserverside-javascript

Cross Domain GET with Marklogic server side js app


There are a lot of questions here involving cross domain requests, CORS, headers, etc. I have tried nearly everything I can find but to no avail. There may be something in the MarkLogic documentation about this but I have wasted hours in there and it is very hard to navigate. Neither are there any MarkLogic examples to follow (that I've been able to find).

[Error] Origin http://localhost:8010 is not allowed by Access-Control- Allow-Origin.
[Error] Failed to load resource: Origin http://localhost:8010 is not allowed by Access-Control-Allow-Origin. (my-js.sjs, line 0)
[Error] XMLHttpRequest cannot load http://localhost:8004/my-js.sjs due to access control checks.

I will try to include all relevant info but tell me if I miss anything.

I am running Mac OS X on Safari with MarkLogic 9 installed. I have an http app server set up hosting at port 8004. I also have a python SimpleHTTPServer running on port 8010. I have a simple html site with a js script that includes the following simple GET request

$("#http-button").click(function(){
    console.log("clicked");
    $.get("http://localhost:8004/my-js.sjs",function(data,status){
        alert("Data: " + data + "\nStatus" + status);
        $("#http-results").text(data);
    })
});`

My server side script, my-js.sjs, is just a simple query. I have included what I though were the necessary headers to allow for cross domain requests but it still doesn't work.

//xdmp.setResponseContentType("text/plain");
xdmp.setResponseContentType("application/json");
xdmp.addResponseHeader('Access-Control-Allow-Origin', '*');
xdmp.addResponseHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xdmp.addResponseHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
xdmp.addResponseHeader('Access-Control-Allow-Credentials', true);

var jsearch = require('/MarkLogic/jsearch.sjs');
//query and print
jsearch.documents()
  .where(
  cts.wordQuery("cardiac")
  ).slice(0,3).result();

I have no idea where to go from here. My implementation is dependent on being able to perform cross domain requests. I was able to do it with node.js and a REST server, but I can't figure out how to do it with server side JavaScript, which is way faster for my purposes.

I am also open to new implementation ideas, but I've already written a lot of the server-side JavaScript, so I would prefer not to have to start over.


Solution

  • Well, sorry if I wasted any time. Turns out these headers did the trick, I just didn't put true

    in quotes.