Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response for preflight has invalid HTTP status code 400

I'm 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>

Initially I got this error: XMLHttpRequest cannot load http://localhost:port/service/myservice. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.

To resolve this issue I added the following code in 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 initial exception went away, but I'm getting the following exception: XMLHttpRequest cannot load http://localhost:port/service/myservice. Response for preflight has invalid HTTP status code 400

Is this issue related to CORS? What am I doing wrong here?

UPDATE

After doing more debugging I found this behavior. When sending the request without the Authorization header I'm getting 415 (Unsupported Media Type) error.

I think something wrong with my AJAX code, can someone please help me find the issue? Thanks.

like image 595
Roy Justin Avatar asked Nov 09 '22 03:11

Roy Justin


1 Answers

You may try here mentioned as complete answer in this thread.

$.ajax({
        type:"POST",
        beforeSend: function (request)
        {
            request.setRequestHeader("Authority", authValue);
        },
        url: "http://localhost:port/service/myservice",
        data: "json=" + escape(JSON.stringify(createRequestObject)),
        processData: false,
        success: function(msg) {
            $("#results").append("The result =" + StringifyPretty(msg));
        }
});
like image 179
Siva Shibhi Avatar answered Nov 14 '22 22:11

Siva Shibhi