I'm working on a restlet built on restlet 1.1.1
The issue I'm facing is setting the 'Access-Control-Allow-Origin' header to allow for cross domain requests. I've attempted a few things that didn't work.
Method one, put the header in the acceptRepresentation function:
@Override
public void acceptRepresentation( Representation resetEntity ) {
Form headers = (Form)getResponse().getAttributes().get("org.restlet.http.headers");
if (headers == null) {
headers = new Form();
getResponse().getAttributes().put("org.restlet.http.headers", headers);
}
headers.add("Access-Control-Allow-Origin","https://origin.server.edu");
//other code here for actual resource logic...
}
This didn't work. I still received errors when attempting to send a request using JQuery as such:
jQuery.ajax({
type: "POST",
contentType: "application/json",
url: "https://test.servername.edu/cas/cas-rest-api/reset/",
data: JSON.stringify("{\"uname\" : \"someone\", \"attr\":\"dataElement\" }"),
dataType: "json",
crossDomain: true
})
.done(function(data){
console.log("Success");
alert(data);
})
.fail(function(data){
console.log("failure");
console.log(data);
alert(data);
});
This didn't work. So I noticed an init function in the resource class. I figured I'd attempt putting my code there to see if this would change the situation.
@Override
public void init(Context context, Request request, Response response ){
Form headers = (Form)response.getAttributes().get("org.restlet.http.headers");
if (headers == null) {
headers = new Form();
response.getAttributes().put("org.restlet.http.headers", headers);
}
headers.add("Access-Control-Allow-Origin","https://origin.server.edu");
super.init(context, request, response);
}
Nope. Didn't work either. What am I missing here? Where do I set this header?
Thanks for your replies. After some analysis of the problem it turned out that I needed to configure Spring to allow option requests for my restlet in the web.xml file as shown below: