通过JQuery在外部域上调用RESTful服务

时间:2016-06-23 10:54:36

标签: java jquery json ajax rest

我试图通过html页面调用Java RESTful服务,但我总是遇到如下错误:

  

否'访问控制 - 允许 - 来源'标头出现在请求的资源上#34;,405(方法不允许)

我最简单的Java代码是:

@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);
}

html代码是:

$('#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);});*/

        });

我试过了:

  1. 有和没有指定java servlet中的响应头
  2. 映射PUT和POST方法
  3. 使用$ .post $ .ajax
  4. 设置dataType json和jsonp
  5. 以及许多其他组合:)

    但是有人为我工作......有什么建议吗?

    注意:正如我在代码中用$ .post写的那样,我得到了错误:No&#39; Access-Control-Allow-Origin,ajax我有错误:405(方法不是允许)

    Thans

1 个答案:

答案 0 :(得分:1)

这里的问题是CORS(跨域支持)有两种类型的请求:

  1. 简单 - 例如HEADGETPOSTPOSTcontent-typeapplication/x-www-form-urlencodedmultipart/form-datatext/plain
  2. 其余请求称为预检请求
  3. 您的CORS请求是Preflight请求。在Preflight请求中,浏览器会触发2个请求:

    1. OPTIONS - 要求服务器验证原点,方法和其他标头是否可信
    2. 实际请求 - 在您的情况下POST
    3. 要解决您的问题,请添加一个处理OPTIONS请求的新映射:

          @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");
          }