我试图通过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);});*/
});
我试过了:
以及许多其他组合:)
但是有人为我工作......有什么建议吗?
注意:正如我在代码中用$ .post写的那样,我得到了错误:No&#39; Access-Control-Allow-Origin,ajax我有错误:405(方法不是允许)
Thans
答案 0 :(得分:1)
这里的问题是CORS
(跨域支持)有两种类型的请求:
HEAD
,GET
和POST
。 POST
与content-type
:application/x-www-form-urlencoded
,multipart/form-data
或text/plain
您的CORS
请求是Preflight请求。在Preflight请求中,浏览器会触发2个请求:
OPTIONS
- 要求服务器验证原点,方法和其他标头是否可信POST
要解决您的问题,请添加一个处理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");
}