Reputation: 87
How to debug this problem ?
This is my java code. I give permission for all ip by setting Access-Control-Allow-Origin, but still it says no "Access-Control-Allow-Origin"
return Response.ok().entity(jsonNodeToSend.toString()).header("Access-Control-Allow-Origin", "*").build();
This is my javascript code.
var dict = {
"clientMac" : "48:43:7c:53:53:d1",
"BSSID" : ""
};
$.ajax({
type: 'POST',
url: 'http://104.155.189.170:8080/Localization/rest/clientMacPosition/get/7',
crossDomain: true,
contentType: "application/json; charset=UTF-8",
data: dict,
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('MessageId', 'abc123');
},
success: function(responseData, textStatus, messageId) {
console.log("success");
},
error: function(responseData, textStatus, errorThrown) {
console.log(textStatus);
console.log(responseData);
console.log(errorThrown);
}
});
Here is my method which gets the data and respond to the request.
@Path("/get/{customerProjectId}")
@POST
@Produces({ MediaType.APPLICATION_JSON })
public Response gettingRecentPosition(LocationAPIReceiverDTO locationAPIReceiverDTO,
@PathParam("customerProjectId") int customerProjectId) {
JsonNode jsonNodeToSend = null;
return Response.ok().entity(jsonNodeToSend.toString()).header("Access-Control-Allow-Origin", "*").build();
}
URL: http://104.155.189.170:8080/Localization/rest/clientMacPosition/get/7
jsonData : { "clientMac" : "48:43:7c:53:53:d1", "BSSID" : "33:" }
My REST call response in POST man.
Upvotes: 1
Views: 673
Reputation: 4074
Please create a filter for your application and add the following header to fix CORS issue:
public class ApplicationFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type,*");
if (httpRequest.getMethod().equals("OPTIONS")) {
httpResponse.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(httpRequest, httpResponse);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
Upvotes: 1
Reputation: 2216
Have you tried to put @CrossOrigin
annotation on your controller method?
Here is an example of how to set up cross origin with spring: https://spring.io/guides/gs/rest-service-cors/
Upvotes: 0