【发布时间】:2020-06-03 11:01:42
【问题描述】:
在 ubuntu 操作系统中使用 Java 11、eclipse、Gradle 和 spring
虽然我的 POST 调用工作正常,但由于 CORS 策略,对服务器的 GET 调用被阻止并出现以下错误:
通过“http://localhost:8080/dices/players?{}”访问 XMLHttpRequest 来自原点“http://localhost”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
POST 和 GET 调用的 javascript 是:
$(document).ready(function(){
$('#newUserButton').click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost:8080/dices/players',
contentType: 'application/json',
xhrFields: { withCredentials: true },
data: JSON.stringify({"name":$('#newUserInput').val()}),
dataType: 'json',
success: function(data) {
$('#newUserJumbo').append('<div class="alert alert-success" role="alert">El usuari ' + data.name + ' ha estat creat</div>');
},
error: function(e){
console.log(e);
}
});
});
});
$(document).ready(function(){
$('#searchUserButton').click(function(){
$.ajax({
type: 'GET',
url: 'http://localhost:8080/dices/players',
contentType: 'application/json',
xhrFields: { withCredentials: true },
data: JSON.stringify({"idPlayer":$('searchUserInput').val()}),
dataType: 'json',
success: function(data) {
$('#modifyUserUl').append('<button type="button" class="list-group-item list-group-item-action" id="' + data.id + ' onclick=modifyUser(' + data.id + '>id: ' + data.id + ', nom: ' + data.name + '</button>');
},
error: function(e){
console.log(e);
}
});
});
});
为了在服务器端处理 CORS,我使用了我在 mozilla mdnwebDoc here 中找到的以下类,该类在 POST 调用中运行良好,但在 GET 上失败
处理GET调用的代码如下:
@CrossOrigin(origins = "http://lvh.me:8080")
@GetMapping("/players/player")
public Player getPlayer(@RequestBody Player newPlayer){
try {
return (Player) repository.findFirstByNameLike(newPlayer.getName());
} catch (EmptyResultDataAccessException e) {
throw new PlayerNotFoundException(newPlayer.getName());
更新 1
正如 Albert 评论的那样,我已将 http://localhost 更改为 http://lvh.me 以查看代码是否有效,但没有退出。 我还编辑了从@PathVariable 更改为@RequestBody 的控制器代码(因为我对具有json 主体的同一个控制器的POST 请求正在工作)也有效。 最后,感谢 Kevin cmets,我还改变了处理 CORS 策略的方式,从全局方法到控制器方法,也没有退出。 我已更改上面的代码以反映此更改。
欢迎任何 cmets 和建议。谢谢 谢谢
【问题讨论】:
标签: java jquery spring gradle cors