Reputation: 11
I am building a webservice with JAX-RS and I have enabled CORS in both server side and the AJAX request, still I get an error saying:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.bookstore.com/orderservice/order. This can be fixed by moving the resource to the same domain or enabling CORS. Any thoughts? Thanks.
Server-Side Code:
<jaxrs:ser <bean id="cors-filter" class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter"/>ver name="OrderService" address="http://www.bookstore.com">
<jaxrs:serviceBeans>
<ref bean="orderServiceRest" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jacksonProvider" />
<ref bean="cors-filter" />
</jaxrs:providers>
<jaxrs:schemaLocations>
< <jaxrs:schemaLocation>com.bookengine.ws.service.representation.OrderRequest</jaxrs:schemaLocation>
<jaxrs:schemaLocation>com.bookengine.ws.service.representation.OrderRepresentation</jaxrs:schemaLocation>
</jaxrs:schemaLocations>
</jaxrs:server>
<bean id="orderServiceRest" class="com.bookengine.ws.service.OrderResource" />
AJAX Request
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control- Allow-Origin': "http://www.bookstore.com/orderservice"
},
type: 'POST',
crossDomain: true,
contentType: 'application/json',
dataType: 'json',
data: '{"orderId":null,"bookId":"X1","status":null,"customer":{"name":"John Smith","address":"312 N State Street, Chicago IL 60611","phone":"312-345-9876","custId":"1234"},"paymentinfo":null}',
url: 'http://bookstore/orderservice/order',
error: function(xhr, status, error) {
// Display a generic error for now.
alert("AJAX Error!");
},
success: function (data) {
var output = "<ul>";
output += "<li>" + "Order ID: " + data.orderID
+ "<br>Book ID: " + data.bookID
+ "<br>Status: " + data.status
+ "</li>";
output += "</ul>";
alert("Hello from sucess");
document.getElementById("buydata").innerHTML = output;
}
});
Upvotes: 0
Views: 413
Reputation: 707148
You can't fix this from the client by adding headers to the sending request.
CORS is enabled from the server where the web-site itself decides what origins are allowed to access it and the CORS headers have to be added by the web-site itself which tells the browser what origins it should permit a request from.
So, you would have to be in control of the http://www.bookstore.com domain and it's server in order to enable CORS on it.
Another cross origin possibility is JSONP, but again the web-site itself has to explicitly support JSONP requests (as they are structured differently than regular requests).
Upvotes: 0
Reputation: 7958
This is security protection in the browser to prevent an Ajax call from one domain to another. You can only prevent this from happening if you own the domain for http://www.bookstore.com/orderservice/order by adding Access-Control-Allow-Origin: to the headers that the server returns or by shifting your webservices to the same domain.
Upvotes: 1