Rest Controller中的删除方法错误问题
我的项目中有一些Rest端点,这些端点是从另一台服务器的客户端应用程序调用的。我已成功使用@CrossOrigin
注释禁用了Cors
,除Delete方法在Chrome上引发以下错误外,所有方法均正常运行:
XMLHttpRequest cannot load
http://localhost:8856/robotpart/1291542214/compatibilities. Response to
preflight request doesn't pass access control check: No 'Access-Control-Allow-
Origin' header is present on the requested resource. Origin
'http://127.0.0.1:8888' is therefore not allowed access. The response had HTTP
status code 403.
这是我的控制器:
@CrossOrigin(origins = "*")@ExposesResourceFor(RobotPart.class)
public class RobotPartController {
//All endpoints are working except the Delete Mapping
@GetMapping("/robotpart")
public ResponseEntity<List<RobotPartResource>> listAllParts() {
//..
}
@GetMapping("/robotpart/{id}")
public ResponseEntity<RobotPartResource> getById(@PathVariable Integer id) {
//..
}
@GetMapping("/robotpart/{id}/compatibilities")
public ResponseEntity<Collection<RobotPartResource>> getRobotCompatibilities(@PathVariable Integer id,
//..
}
@PostMapping("/robotpart")
public ResponseEntity<RobotPartResource> getById(@RequestBody @Valid RobotPart newRobot) {
//..
@PutMapping("/robotpart/{id}")
public ResponseEntity<RobotPartResource> modify(@PathVariable Integer id, @Valid @RequestBody RobotPart newRobot) {
//...
}
@DeleteMapping("/robotpart/{id}")
public ResponseEntity<RobotPart> deleteById(@PathVariable Integer id) {
//...
}
}
可以解决吗?
回答:
在分析http请求之后,我找到了一个解决方案,我注意到Access-Control-Allow-
Methods标头缺少DELETE方法,因此我通过删除@CrossOrigin
批注来添加它,并将此bean添加到配置中:
@Bean public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/robotpart/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE");
}
};
}
以上是 Rest Controller中的删除方法错误问题 的全部内容, 来源链接: utcz.com/qa/407908.html