【发布时间】:2019-11-17 18:50:39
【问题描述】:
我使用带有 rest API 的 Spring Boot 2 制作了一些 Web 项目。我有两个项目,一个是rest API,另一个是web项目调用rest API。我已经在使用@CrossOrigin(origins = "*")。所以,它在控制器类中运行良好。
但是,当我向其他控制器类调用请求时,chrome 将其打印给我,Access to XMLHttpRequest at 'http://localhost:8080/signout/1234' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.。我该如何解决这个问题?
这是我的工作控制器类。盲区没有其他特别之处:
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/admin")
public class AdminController {
...
@PutMapping("/users")
public User updateUser(@Valid @RequestBody User updatedUser) throws ResourceNotFoundException {
User savedUser = userRepository.findByUsername(updatedUser.getUsername());
savedUser.setPassword(updatedUser.getPassword());
savedUser = userRepository.save(savedUser);
return savedUser;
}
...
}
这是工作 ajax:
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
...
} else if (this.status == 500) {
alert(this.responseText);
}
}
var json = JSON.stringify(param);
xmlHttp.open("POST", mainurl+"admin/role", false);
xmlHttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
xmlHttp.send(json);
这不是工作控制器。一开始我只是用了`@CrossOrigin(origins = "*")。
//@CrossOrigin(origins = "http://localhost:8081", allowedHeaders = "*")
@CrossOrigin(origins = "*", allowCredentials = "true", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
@RestController
@RequestMapping("/")
public class UserController {
...
}
这不适用于 JWT 的 ajax。
$.ajax({
type: "DELETE",
url: "http://localhost:8080/signout/"+username,
async: true,
// crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Bearer '+ "${token}");
},
success: function(result, status, xhr){
//service 표시
},
error: function(xhr, status, err) {
alert(xhr.responseText);
}
});
// var xmlHttp = new XMLHttpRequest();
// xmlHttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200){
// location.href=window.location.protocol + "//" + window.location.host + "/sso_ui/";
// } else if (this.status == 500) {
// alert(this.responseText);
// }
// }
// xmlHttp.open("DELETE", "http://localhost:8080/signout/"+username, false);
// xmlHttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
// xmlHttp.setRequestHeader('Authorization', 'Bearer ' + "${token}");
// xmlHttp.send();
我该如何解决这个问题?
【问题讨论】:
-
预检请求是 OPTIONS 请求,您没有在允许的方法中列出该请求。
标签: javascript spring spring-boot cors