我正在开发一个CRUD应用程序,它将在SpringBoot部分中提供REST (它也将有一个Angular部分,使用JSON)。SpringBoot部分很好地服务于JSON (针对MySQL数据库的查询),但是当我运行试图删除记录的部分时,我得到了一个405错误:
出现意外错误(不允许type=Method,status=405)。
这是失败的代码(它调用@Service)
@RequestMapping(value = "/avisos/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> borraAviso(@RequestParam("id") Long id) {
boolean isRemoved;
isRemoved = avisoService.borraAviso(id);
if (!isRemoved) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
else
return new ResponseEntity<>(HttpStatus.OK);
}下面是CORS配置文件:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration implements WebMvcConfigurer
{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
//.allowedMethods("GET", "POST");
.allowedMethods("");
}
}该程序在Linux Mint box中运行,但我也在W8 box中进行了测试,我得到了相同的错误。(我使用的是Spring Tool Suite4,版本: 4.8.0.RELEASE和Maven)。
发布于 2020-10-06 18:34:25
该方法的声明有一个问题
@RequestMapping(value = "/avisos/delete/{id}",method = RequestMethod.DELETE)公共ResponseEntity borraAviso(@RequestParam("id")长id) {
这里的id是一个PathVariable。所以正确的声明应该是
@RequestMapping(value = "/avisos/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Void> borraAviso(@PathVariable("id") Long id) {默认情况下,CORS允许使用GET、HEAD和POST方法。
如果您想要允许DELETE方法,那么下面的配置应该有效。
registry.addMapping("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods(HttpMethod.GET.name(),
HttpMethod.HEAD.name(),
HttpMethod.POST.name(),
HttpMethod.DELETE.name()
);https://stackoverflow.com/questions/64223467
复制相似问题