1

I'm trying to calling a Java RESTful service by an html page, but I always get errors like the below:

No 'Access-Control-Allow-Origin' header is present on the requested resource", 405 (Method Not Allowed)

My simplest Java code is:

@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/prenotazioni/{id}", method = RequestMethod.POST)
public ResponseEntity<Prenotazione> updatePrenotazione(HttpServletResponse response, @PathVariable int id, @RequestBody Prenotazione obj) {

    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");

    try {
        prenotazioneService.updatePrenotazione(id, obj);
    } catch (Exception e) {
        return new ResponseEntity(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Prenotazione>(obj,HttpStatus.OK);
}

And the html code is:

$('#btnSalva').on('click', function(e){
            //Creo la stringa JSON nel formato atteso dal servizio RESTful
            var obj = '{"aula":{"id":' + $("#id_aula").val() + '},"id_utente":1,"data_inizio":"' + $("#datetimepicker1").data().DateTimePicker.date() + '","data_fine":"' + $("#datetimepicker2").data().DateTimePicker.date() + '"}';
            var id = $("#id_evento").val();
            var url = "http://localhost:8080/gestione_aule/prenotazioni/" + id;
            //With $.post I've got error: No 'Access-Control-Allow-Origin
            $.post( "http://localhost:8080/gestione_aule/prenotazioni/" + id, obj );
            //With $.ajax I've got error: 405 (Method Not Allowed)
            /*$.ajax({
                url: "http://localhost:8080/gestione_aule/prenotazioni/" + id,
                type: "POST",
                crossDomain: true,
                data: obj,
                dataType: "jsonp",
                success:function(result){
                    alert(JSON.stringify(result));
                },
                error:function(xhr,status,error){
                    alert(status);
                }
                });*/
            /*$.postJSON = function(url, data, callback) {
                return jQuery.ajax({
                headers: { 
                'Accept': 'application/json',
                'Content-Type': 'application/json' 
                },
                'type': 'get',
                'url': url,
                'data': JSON.stringify(data),
                'dataType': 'jsonp',
                'complete': function(e){
                        alert("c " + e);
                    },
                'success': function(e){
                        alert("s " + e);
                    },
                'error': function(e){
                        alert("e " + e);
                    }           
                });
            };

            $.postJSON(url, obj, function(e){alert(e);});*/

        });

I've tried:

  1. with and without specify response header in java servlet
  2. mapping PUT and POST method
  3. using $.post $.ajax
  4. setting dataType json and jsonp

and many other combinations :)

But anyone worked for me... any suggest please?

Note: as I wrote in the code with $.post I've got error: No 'Access-Control-Allow-Origin, with ajax I've got error: 405 (Method Not Allowed)

Thans

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Alessandro
  • 4,382
  • 8
  • 36
  • 70

1 Answers1

1

The problem here that CORS (cross domain support) has 2 types of request:

  1. Simple - such as HEAD, GET and POST. POST with content-type: application/x-www-form-urlencoded, multipart/form-data or text/plain
  2. The rest requests are called Preflight requests

Your CORS request is a Preflight one. In Preflight requests the browser fires 2 requests:

  1. OPTIONS - asking the server to verify that the origin, method and additional headers are trusted
  2. The actual request - in your case POST

To fix the issue your case, add a new mapping that will handle the OPTIONS request:

    @RequestMapping(value = "/prenotazioni/{id}", method = RequestMethod.OPTIONS)
    public void updatePrenotazione(HttpServletResponse response, @PathVariable int id) {

        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        response.addHeader("Access-Control-Allow-Headers", "accept, content-Type");
    }
shachar
  • 641
  • 5
  • 12
  • Hi shacar, I don't know why but it doesn't work yet... now error's: 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. I'm using a caller like this: $.ajax({type: "POST",dataType: "json",contentType: 'application/json',crossDomain : true,etc... – Alessandro Jun 23 '16 at 15:00
  • 1
    This should do the final trick: http://stackoverflow.com/a/9521717/1906800 – shachar Jun 24 '16 at 04:55
  • It worked! I set "dispatchOptionsRequest" param to "true" in my web.xml file, thank you so much – Alessandro Jun 24 '16 at 07:11