I am trying to make a REST call (POST) using AJAX. This is my AJAX code
<script> var settings = { "async": true, "crossDomain": true, "dataType": "json", "url": "http://localhost:port/service/myservice", "method": "POST", "data": '{jsondata}', "headers": { "accept": "application/json", "Authorization": "authValue" } } $.ajax(settings) .done(function (response) { console.log(response); }); </script>
I originally got this error: XMLHttpRequest cannot load http: // localhost: port / service / myservice . The response to the request before the flight does not pass the access control check. There is no "Access-Control-Allow-Origin" header on the requested resource. Therefore, the original 'null' is not allowed. The response was an HTTP 400 status code.
To solve this problem, I added the following code to my dropwizard application
Dynamic filter = env.servlets().addFilter("CORS", CrossOriginFilter.class); filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS"); filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin"); filter.setInitParameter("allowCredentials", "true"); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "
After adding this, my original exception went away, but I get the following exception: XMLHttpRequest cannot load http: // localhost: port / service / myservice . Preflight response has an invalid HTTP 400 status code
Is this a problem with CORS? What am I doing wrong here?
UPDATE
After doing additional debugging, I found this behavior. When sending a request without an authorization header, I get 415 (Unsupported media type) .
I think something is wrong with my AJAX code, can someone please help me find the problem? Thanks.